babylon.max.js 2.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650
  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. var KeyboardEventTypes = (function () {
  20. function KeyboardEventTypes() {
  21. }
  22. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  23. get: function () {
  24. return KeyboardEventTypes._KEYDOWN;
  25. },
  26. enumerable: true,
  27. configurable: true
  28. });
  29. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  30. get: function () {
  31. return KeyboardEventTypes._KEYUP;
  32. },
  33. enumerable: true,
  34. configurable: true
  35. });
  36. KeyboardEventTypes._KEYDOWN = 0x01;
  37. KeyboardEventTypes._KEYUP = 0x02;
  38. return KeyboardEventTypes;
  39. }());
  40. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  41. var KeyboardInfo = (function () {
  42. function KeyboardInfo(type, event) {
  43. this.type = type;
  44. this.event = event;
  45. }
  46. return KeyboardInfo;
  47. }());
  48. BABYLON.KeyboardInfo = KeyboardInfo;
  49. /**
  50. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  51. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  52. */
  53. var KeyboardInfoPre = (function (_super) {
  54. __extends(KeyboardInfoPre, _super);
  55. function KeyboardInfoPre(type, event) {
  56. var _this = _super.call(this, type, event) || this;
  57. _this.skipOnPointerObservable = false;
  58. return _this;
  59. }
  60. return KeyboardInfoPre;
  61. }(KeyboardInfo));
  62. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  63. })(BABYLON || (BABYLON = {}));
  64. //# sourceMappingURL=babylon.keyboardEvents.js.map
  65. var BABYLON;
  66. (function (BABYLON) {
  67. var PointerEventTypes = (function () {
  68. function PointerEventTypes() {
  69. }
  70. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  71. get: function () {
  72. return PointerEventTypes._POINTERDOWN;
  73. },
  74. enumerable: true,
  75. configurable: true
  76. });
  77. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  78. get: function () {
  79. return PointerEventTypes._POINTERUP;
  80. },
  81. enumerable: true,
  82. configurable: true
  83. });
  84. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  85. get: function () {
  86. return PointerEventTypes._POINTERMOVE;
  87. },
  88. enumerable: true,
  89. configurable: true
  90. });
  91. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  92. get: function () {
  93. return PointerEventTypes._POINTERWHEEL;
  94. },
  95. enumerable: true,
  96. configurable: true
  97. });
  98. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  99. get: function () {
  100. return PointerEventTypes._POINTERPICK;
  101. },
  102. enumerable: true,
  103. configurable: true
  104. });
  105. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  106. get: function () {
  107. return PointerEventTypes._POINTERTAP;
  108. },
  109. enumerable: true,
  110. configurable: true
  111. });
  112. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  113. get: function () {
  114. return PointerEventTypes._POINTERDOUBLETAP;
  115. },
  116. enumerable: true,
  117. configurable: true
  118. });
  119. PointerEventTypes._POINTERDOWN = 0x01;
  120. PointerEventTypes._POINTERUP = 0x02;
  121. PointerEventTypes._POINTERMOVE = 0x04;
  122. PointerEventTypes._POINTERWHEEL = 0x08;
  123. PointerEventTypes._POINTERPICK = 0x10;
  124. PointerEventTypes._POINTERTAP = 0x20;
  125. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  126. return PointerEventTypes;
  127. }());
  128. BABYLON.PointerEventTypes = PointerEventTypes;
  129. var PointerInfoBase = (function () {
  130. function PointerInfoBase(type, event) {
  131. this.type = type;
  132. this.event = event;
  133. }
  134. return PointerInfoBase;
  135. }());
  136. BABYLON.PointerInfoBase = PointerInfoBase;
  137. /**
  138. * This class is used to store pointer related info for the onPrePointerObservable event.
  139. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  140. */
  141. var PointerInfoPre = (function (_super) {
  142. __extends(PointerInfoPre, _super);
  143. function PointerInfoPre(type, event, localX, localY) {
  144. var _this = _super.call(this, type, event) || this;
  145. _this.skipOnPointerObservable = false;
  146. _this.localPosition = new BABYLON.Vector2(localX, localY);
  147. return _this;
  148. }
  149. return PointerInfoPre;
  150. }(PointerInfoBase));
  151. BABYLON.PointerInfoPre = PointerInfoPre;
  152. /**
  153. * This type contains all the data related to a pointer event in Babylon.js.
  154. * 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.
  155. */
  156. var PointerInfo = (function (_super) {
  157. __extends(PointerInfo, _super);
  158. function PointerInfo(type, event, pickInfo) {
  159. var _this = _super.call(this, type, event) || this;
  160. _this.pickInfo = pickInfo;
  161. return _this;
  162. }
  163. return PointerInfo;
  164. }(PointerInfoBase));
  165. BABYLON.PointerInfo = PointerInfo;
  166. })(BABYLON || (BABYLON = {}));
  167. //# sourceMappingURL=babylon.pointerEvents.js.map
  168. var BABYLON;
  169. (function (BABYLON) {
  170. BABYLON.ToGammaSpace = 1 / 2.2;
  171. BABYLON.ToLinearSpace = 2.2;
  172. BABYLON.Epsilon = 0.001;
  173. var Color3 = (function () {
  174. /**
  175. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  176. */
  177. function Color3(r, g, b) {
  178. if (r === void 0) { r = 0; }
  179. if (g === void 0) { g = 0; }
  180. if (b === void 0) { b = 0; }
  181. this.r = r;
  182. this.g = g;
  183. this.b = b;
  184. }
  185. /**
  186. * Returns a string with the Color3 current values.
  187. */
  188. Color3.prototype.toString = function () {
  189. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  190. };
  191. /**
  192. * Returns the string "Color3".
  193. */
  194. Color3.prototype.getClassName = function () {
  195. return "Color3";
  196. };
  197. /**
  198. * Returns the Color3 hash code.
  199. */
  200. Color3.prototype.getHashCode = function () {
  201. var hash = this.r || 0;
  202. hash = (hash * 397) ^ (this.g || 0);
  203. hash = (hash * 397) ^ (this.b || 0);
  204. return hash;
  205. };
  206. // Operators
  207. /**
  208. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  209. * Returns the Color3.
  210. */
  211. Color3.prototype.toArray = function (array, index) {
  212. if (index === undefined) {
  213. index = 0;
  214. }
  215. array[index] = this.r;
  216. array[index + 1] = this.g;
  217. array[index + 2] = this.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color4 object from the current Color3 and the passed alpha.
  222. */
  223. Color3.prototype.toColor4 = function (alpha) {
  224. if (alpha === void 0) { alpha = 1; }
  225. return new Color4(this.r, this.g, this.b, alpha);
  226. };
  227. /**
  228. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  229. */
  230. Color3.prototype.asArray = function () {
  231. var result = [];
  232. this.toArray(result, 0);
  233. return result;
  234. };
  235. /**
  236. * Returns the luminance value (float).
  237. */
  238. Color3.prototype.toLuminance = function () {
  239. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  240. };
  241. /**
  242. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  243. * Returns this new object.
  244. */
  245. Color3.prototype.multiply = function (otherColor) {
  246. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  247. };
  248. /**
  249. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  250. * Returns the current Color3.
  251. */
  252. Color3.prototype.multiplyToRef = function (otherColor, result) {
  253. result.r = this.r * otherColor.r;
  254. result.g = this.g * otherColor.g;
  255. result.b = this.b * otherColor.b;
  256. return this;
  257. };
  258. /**
  259. * Boolean : True if the rgb values are equal to the passed ones.
  260. */
  261. Color3.prototype.equals = function (otherColor) {
  262. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  263. };
  264. /**
  265. * Boolean : True if the rgb values are equal to the passed ones.
  266. */
  267. Color3.prototype.equalsFloats = function (r, g, b) {
  268. return this.r === r && this.g === g && this.b === b;
  269. };
  270. /**
  271. * Multiplies in place each rgb value by scale.
  272. * Returns the updated Color3.
  273. */
  274. Color3.prototype.scale = function (scale) {
  275. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  276. };
  277. /**
  278. * Multiplies the rgb values by scale and stores the result into "result".
  279. * Returns the unmodified current Color3.
  280. */
  281. Color3.prototype.scaleToRef = function (scale, result) {
  282. result.r = this.r * scale;
  283. result.g = this.g * scale;
  284. result.b = this.b * scale;
  285. return this;
  286. };
  287. /**
  288. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  289. */
  290. Color3.prototype.add = function (otherColor) {
  291. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  292. };
  293. /**
  294. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  295. * Returns the unmodified current Color3.
  296. */
  297. Color3.prototype.addToRef = function (otherColor, result) {
  298. result.r = this.r + otherColor.r;
  299. result.g = this.g + otherColor.g;
  300. result.b = this.b + otherColor.b;
  301. return this;
  302. };
  303. /**
  304. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  305. */
  306. Color3.prototype.subtract = function (otherColor) {
  307. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  308. };
  309. /**
  310. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  311. * Returns the unmodified current Color3.
  312. */
  313. Color3.prototype.subtractToRef = function (otherColor, result) {
  314. result.r = this.r - otherColor.r;
  315. result.g = this.g - otherColor.g;
  316. result.b = this.b - otherColor.b;
  317. return this;
  318. };
  319. /**
  320. * Returns a new Color3 copied the current one.
  321. */
  322. Color3.prototype.clone = function () {
  323. return new Color3(this.r, this.g, this.b);
  324. };
  325. /**
  326. * Copies the rgb values from the source in the current Color3.
  327. * Returns the updated Color3.
  328. */
  329. Color3.prototype.copyFrom = function (source) {
  330. this.r = source.r;
  331. this.g = source.g;
  332. this.b = source.b;
  333. return this;
  334. };
  335. /**
  336. * Updates the Color3 rgb values from the passed floats.
  337. * Returns the Color3.
  338. */
  339. Color3.prototype.copyFromFloats = function (r, g, b) {
  340. this.r = r;
  341. this.g = g;
  342. this.b = b;
  343. return this;
  344. };
  345. /**
  346. * Updates the Color3 rgb values from the passed floats.
  347. * Returns the Color3.
  348. */
  349. Color3.prototype.set = function (r, g, b) {
  350. return this.copyFromFloats(r, g, b);
  351. };
  352. /**
  353. * Returns the Color3 hexadecimal code as a string.
  354. */
  355. Color3.prototype.toHexString = function () {
  356. var intR = (this.r * 255) | 0;
  357. var intG = (this.g * 255) | 0;
  358. var intB = (this.b * 255) | 0;
  359. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  360. };
  361. /**
  362. * Returns a new Color3 converted to linear space.
  363. */
  364. Color3.prototype.toLinearSpace = function () {
  365. var convertedColor = new Color3();
  366. this.toLinearSpaceToRef(convertedColor);
  367. return convertedColor;
  368. };
  369. /**
  370. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  371. * Returns the unmodified Color3.
  372. */
  373. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  374. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  375. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  376. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  377. return this;
  378. };
  379. /**
  380. * Returns a new Color3 converted to gamma space.
  381. */
  382. Color3.prototype.toGammaSpace = function () {
  383. var convertedColor = new Color3();
  384. this.toGammaSpaceToRef(convertedColor);
  385. return convertedColor;
  386. };
  387. /**
  388. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  389. * Returns the unmodified Color3.
  390. */
  391. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  392. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  393. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  394. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  395. return this;
  396. };
  397. // Statics
  398. /**
  399. * Creates a new Color3 from the string containing valid hexadecimal values.
  400. */
  401. Color3.FromHexString = function (hex) {
  402. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  403. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  404. return new Color3(0, 0, 0);
  405. }
  406. var r = parseInt(hex.substring(1, 3), 16);
  407. var g = parseInt(hex.substring(3, 5), 16);
  408. var b = parseInt(hex.substring(5, 7), 16);
  409. return Color3.FromInts(r, g, b);
  410. };
  411. /**
  412. * Creates a new Vector3 from the startind index of the passed array.
  413. */
  414. Color3.FromArray = function (array, offset) {
  415. if (offset === void 0) { offset = 0; }
  416. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  417. };
  418. /**
  419. * Creates a new Color3 from integer values ( < 256).
  420. */
  421. Color3.FromInts = function (r, g, b) {
  422. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  423. };
  424. /**
  425. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  426. */
  427. Color3.Lerp = function (start, end, amount) {
  428. var r = start.r + ((end.r - start.r) * amount);
  429. var g = start.g + ((end.g - start.g) * amount);
  430. var b = start.b + ((end.b - start.b) * amount);
  431. return new Color3(r, g, b);
  432. };
  433. Color3.Red = function () { return new Color3(1, 0, 0); };
  434. Color3.Green = function () { return new Color3(0, 1, 0); };
  435. Color3.Blue = function () { return new Color3(0, 0, 1); };
  436. Color3.Black = function () { return new Color3(0, 0, 0); };
  437. Color3.White = function () { return new Color3(1, 1, 1); };
  438. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  439. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  440. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  441. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  442. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  443. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  444. return Color3;
  445. }());
  446. BABYLON.Color3 = Color3;
  447. var Color4 = (function () {
  448. /**
  449. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  450. */
  451. function Color4(r, g, b, a) {
  452. if (r === void 0) { r = 0; }
  453. if (g === void 0) { g = 0; }
  454. if (b === void 0) { b = 0; }
  455. if (a === void 0) { a = 1; }
  456. this.r = r;
  457. this.g = g;
  458. this.b = b;
  459. this.a = a;
  460. }
  461. // Operators
  462. /**
  463. * Adds in place the passed Color4 values to the current Color4.
  464. * Returns the updated Color4.
  465. */
  466. Color4.prototype.addInPlace = function (right) {
  467. this.r += right.r;
  468. this.g += right.g;
  469. this.b += right.b;
  470. this.a += right.a;
  471. return this;
  472. };
  473. /**
  474. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  475. */
  476. Color4.prototype.asArray = function () {
  477. var result = [];
  478. this.toArray(result, 0);
  479. return result;
  480. };
  481. /**
  482. * Stores from the starting index in the passed array the Color4 successive values.
  483. * Returns the Color4.
  484. */
  485. Color4.prototype.toArray = function (array, index) {
  486. if (index === undefined) {
  487. index = 0;
  488. }
  489. array[index] = this.r;
  490. array[index + 1] = this.g;
  491. array[index + 2] = this.b;
  492. array[index + 3] = this.a;
  493. return this;
  494. };
  495. /**
  496. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  497. */
  498. Color4.prototype.add = function (right) {
  499. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  500. };
  501. /**
  502. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  503. */
  504. Color4.prototype.subtract = function (right) {
  505. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  506. };
  507. /**
  508. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  509. * Returns the Color4.
  510. */
  511. Color4.prototype.subtractToRef = function (right, result) {
  512. result.r = this.r - right.r;
  513. result.g = this.g - right.g;
  514. result.b = this.b - right.b;
  515. result.a = this.a - right.a;
  516. return this;
  517. };
  518. /**
  519. * Creates a new Color4 with the current Color4 values multiplied by scale.
  520. */
  521. Color4.prototype.scale = function (scale) {
  522. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  523. };
  524. /**
  525. * Multiplies the current Color4 values by scale and stores the result in "result".
  526. * Returns the Color4.
  527. */
  528. Color4.prototype.scaleToRef = function (scale, result) {
  529. result.r = this.r * scale;
  530. result.g = this.g * scale;
  531. result.b = this.b * scale;
  532. result.a = this.a * scale;
  533. return this;
  534. };
  535. /**
  536. * Multipy an RGBA Color4 value by another and return a new Color4 object
  537. * @param color The Color4 (RGBA) value to multiply by
  538. * @returns A new Color4.
  539. */
  540. Color4.prototype.multiply = function (color) {
  541. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  542. };
  543. /**
  544. * Multipy an RGBA Color4 value by another and push the result in a reference value
  545. * @param color The Color4 (RGBA) value to multiply by
  546. * @param result The Color4 (RGBA) to fill the result in
  547. * @returns the result Color4.
  548. */
  549. Color4.prototype.multiplyToRef = function (color, result) {
  550. result.r = this.r * color.r;
  551. result.g = this.g * color.g;
  552. result.b = this.b * color.b;
  553. result.a = this.a * color.a;
  554. return result;
  555. };
  556. /**
  557. * Returns a string with the Color4 values.
  558. */
  559. Color4.prototype.toString = function () {
  560. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  561. };
  562. /**
  563. * Returns the string "Color4"
  564. */
  565. Color4.prototype.getClassName = function () {
  566. return "Color4";
  567. };
  568. /**
  569. * Return the Color4 hash code as a number.
  570. */
  571. Color4.prototype.getHashCode = function () {
  572. var hash = this.r || 0;
  573. hash = (hash * 397) ^ (this.g || 0);
  574. hash = (hash * 397) ^ (this.b || 0);
  575. hash = (hash * 397) ^ (this.a || 0);
  576. return hash;
  577. };
  578. /**
  579. * Creates a new Color4 copied from the current one.
  580. */
  581. Color4.prototype.clone = function () {
  582. return new Color4(this.r, this.g, this.b, this.a);
  583. };
  584. /**
  585. * Copies the passed Color4 values into the current one.
  586. * Returns the updated Color4.
  587. */
  588. Color4.prototype.copyFrom = function (source) {
  589. this.r = source.r;
  590. this.g = source.g;
  591. this.b = source.b;
  592. this.a = source.a;
  593. return this;
  594. };
  595. /**
  596. * Copies the passed float values into the current one.
  597. * Returns the updated Color4.
  598. */
  599. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  600. this.r = r;
  601. this.g = g;
  602. this.b = b;
  603. this.a = a;
  604. return this;
  605. };
  606. /**
  607. * Copies the passed float values into the current one.
  608. * Returns the updated Color4.
  609. */
  610. Color4.prototype.set = function (r, g, b, a) {
  611. return this.copyFromFloats(r, g, b, a);
  612. };
  613. /**
  614. * Returns a string containing the hexadecimal Color4 code.
  615. */
  616. Color4.prototype.toHexString = function () {
  617. var intR = (this.r * 255) | 0;
  618. var intG = (this.g * 255) | 0;
  619. var intB = (this.b * 255) | 0;
  620. var intA = (this.a * 255) | 0;
  621. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  622. };
  623. /**
  624. * Returns a new Color4 converted to linear space.
  625. */
  626. Color4.prototype.toLinearSpace = function () {
  627. var convertedColor = new Color4();
  628. this.toLinearSpaceToRef(convertedColor);
  629. return convertedColor;
  630. };
  631. /**
  632. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  633. * Returns the unmodified Color4.
  634. */
  635. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  636. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  637. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  638. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  639. convertedColor.a = this.a;
  640. return this;
  641. };
  642. /**
  643. * Returns a new Color4 converted to gamma space.
  644. */
  645. Color4.prototype.toGammaSpace = function () {
  646. var convertedColor = new Color4();
  647. this.toGammaSpaceToRef(convertedColor);
  648. return convertedColor;
  649. };
  650. /**
  651. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  652. * Returns the unmodified Color4.
  653. */
  654. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  655. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  656. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  657. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  658. convertedColor.a = this.a;
  659. return this;
  660. };
  661. // Statics
  662. /**
  663. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  664. */
  665. Color4.FromHexString = function (hex) {
  666. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  667. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  668. return new Color4(0.0, 0.0, 0.0, 0.0);
  669. }
  670. var r = parseInt(hex.substring(1, 3), 16);
  671. var g = parseInt(hex.substring(3, 5), 16);
  672. var b = parseInt(hex.substring(5, 7), 16);
  673. var a = parseInt(hex.substring(7, 9), 16);
  674. return Color4.FromInts(r, g, b, a);
  675. };
  676. /**
  677. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  678. */
  679. Color4.Lerp = function (left, right, amount) {
  680. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  681. Color4.LerpToRef(left, right, amount, result);
  682. return result;
  683. };
  684. /**
  685. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  686. */
  687. Color4.LerpToRef = function (left, right, amount, result) {
  688. result.r = left.r + (right.r - left.r) * amount;
  689. result.g = left.g + (right.g - left.g) * amount;
  690. result.b = left.b + (right.b - left.b) * amount;
  691. result.a = left.a + (right.a - left.a) * amount;
  692. };
  693. /**
  694. * Creates a new Color4 from the starting index element of the passed array.
  695. */
  696. Color4.FromArray = function (array, offset) {
  697. if (offset === void 0) { offset = 0; }
  698. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  699. };
  700. /**
  701. * Creates a new Color4 from the passed integers ( < 256 ).
  702. */
  703. Color4.FromInts = function (r, g, b, a) {
  704. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  705. };
  706. Color4.CheckColors4 = function (colors, count) {
  707. // Check if color3 was used
  708. if (colors.length === count * 3) {
  709. var colors4 = [];
  710. for (var index = 0; index < colors.length; index += 3) {
  711. var newIndex = (index / 3) * 4;
  712. colors4[newIndex] = colors[index];
  713. colors4[newIndex + 1] = colors[index + 1];
  714. colors4[newIndex + 2] = colors[index + 2];
  715. colors4[newIndex + 3] = 1.0;
  716. }
  717. return colors4;
  718. }
  719. return colors;
  720. };
  721. return Color4;
  722. }());
  723. BABYLON.Color4 = Color4;
  724. var Vector2 = (function () {
  725. /**
  726. * Creates a new Vector2 from the passed x and y coordinates.
  727. */
  728. function Vector2(x, y) {
  729. this.x = x;
  730. this.y = y;
  731. }
  732. /**
  733. * Returns a string with the Vector2 coordinates.
  734. */
  735. Vector2.prototype.toString = function () {
  736. return "{X: " + this.x + " Y:" + this.y + "}";
  737. };
  738. /**
  739. * Returns the string "Vector2"
  740. */
  741. Vector2.prototype.getClassName = function () {
  742. return "Vector2";
  743. };
  744. /**
  745. * Returns the Vector2 hash code as a number.
  746. */
  747. Vector2.prototype.getHashCode = function () {
  748. var hash = this.x || 0;
  749. hash = (hash * 397) ^ (this.y || 0);
  750. return hash;
  751. };
  752. // Operators
  753. /**
  754. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  755. * Returns the Vector2.
  756. */
  757. Vector2.prototype.toArray = function (array, index) {
  758. if (index === void 0) { index = 0; }
  759. array[index] = this.x;
  760. array[index + 1] = this.y;
  761. return this;
  762. };
  763. /**
  764. * Returns a new array with 2 elements : the Vector2 coordinates.
  765. */
  766. Vector2.prototype.asArray = function () {
  767. var result = [];
  768. this.toArray(result, 0);
  769. return result;
  770. };
  771. /**
  772. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  773. * Returns the updated Vector2.
  774. */
  775. Vector2.prototype.copyFrom = function (source) {
  776. this.x = source.x;
  777. this.y = source.y;
  778. return this;
  779. };
  780. /**
  781. * Sets the Vector2 coordinates with the passed floats.
  782. * Returns the updated Vector2.
  783. */
  784. Vector2.prototype.copyFromFloats = function (x, y) {
  785. this.x = x;
  786. this.y = y;
  787. return this;
  788. };
  789. /**
  790. * Sets the Vector2 coordinates with the passed floats.
  791. * Returns the updated Vector2.
  792. */
  793. Vector2.prototype.set = function (x, y) {
  794. return this.copyFromFloats(x, y);
  795. };
  796. /**
  797. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  798. */
  799. Vector2.prototype.add = function (otherVector) {
  800. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  801. };
  802. /**
  803. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  804. * Returns the Vector2.
  805. */
  806. Vector2.prototype.addToRef = function (otherVector, result) {
  807. result.x = this.x + otherVector.x;
  808. result.y = this.y + otherVector.y;
  809. return this;
  810. };
  811. /**
  812. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  813. * Returns the updated Vector2.
  814. */
  815. Vector2.prototype.addInPlace = function (otherVector) {
  816. this.x += otherVector.x;
  817. this.y += otherVector.y;
  818. return this;
  819. };
  820. /**
  821. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  822. */
  823. Vector2.prototype.addVector3 = function (otherVector) {
  824. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  825. };
  826. /**
  827. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  828. */
  829. Vector2.prototype.subtract = function (otherVector) {
  830. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  831. };
  832. /**
  833. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  834. * Returns the Vector2.
  835. */
  836. Vector2.prototype.subtractToRef = function (otherVector, result) {
  837. result.x = this.x - otherVector.x;
  838. result.y = this.y - otherVector.y;
  839. return this;
  840. };
  841. /**
  842. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  843. * Returns the updated Vector2.
  844. */
  845. Vector2.prototype.subtractInPlace = function (otherVector) {
  846. this.x -= otherVector.x;
  847. this.y -= otherVector.y;
  848. return this;
  849. };
  850. /**
  851. * Multiplies in place the current Vector2 coordinates by the passed ones.
  852. * Returns the updated Vector2.
  853. */
  854. Vector2.prototype.multiplyInPlace = function (otherVector) {
  855. this.x *= otherVector.x;
  856. this.y *= otherVector.y;
  857. return this;
  858. };
  859. /**
  860. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  861. */
  862. Vector2.prototype.multiply = function (otherVector) {
  863. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  864. };
  865. /**
  866. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  867. * Returns the Vector2.
  868. */
  869. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  870. result.x = this.x * otherVector.x;
  871. result.y = this.y * otherVector.y;
  872. return this;
  873. };
  874. /**
  875. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  876. */
  877. Vector2.prototype.multiplyByFloats = function (x, y) {
  878. return new Vector2(this.x * x, this.y * y);
  879. };
  880. /**
  881. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  882. */
  883. Vector2.prototype.divide = function (otherVector) {
  884. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  885. };
  886. /**
  887. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  888. * Returns the Vector2.
  889. */
  890. Vector2.prototype.divideToRef = function (otherVector, result) {
  891. result.x = this.x / otherVector.x;
  892. result.y = this.y / otherVector.y;
  893. return this;
  894. };
  895. /**
  896. * Returns a new Vector2 with current Vector2 negated coordinates.
  897. */
  898. Vector2.prototype.negate = function () {
  899. return new Vector2(-this.x, -this.y);
  900. };
  901. /**
  902. * Multiply the Vector2 coordinates by scale.
  903. * Returns the updated Vector2.
  904. */
  905. Vector2.prototype.scaleInPlace = function (scale) {
  906. this.x *= scale;
  907. this.y *= scale;
  908. return this;
  909. };
  910. /**
  911. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  912. */
  913. Vector2.prototype.scale = function (scale) {
  914. return new Vector2(this.x * scale, this.y * scale);
  915. };
  916. /**
  917. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  918. */
  919. Vector2.prototype.equals = function (otherVector) {
  920. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  921. };
  922. /**
  923. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  924. */
  925. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  926. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  927. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  928. };
  929. // Properties
  930. /**
  931. * Returns the vector length (float).
  932. */
  933. Vector2.prototype.length = function () {
  934. return Math.sqrt(this.x * this.x + this.y * this.y);
  935. };
  936. /**
  937. * Returns the vector squared length (float);
  938. */
  939. Vector2.prototype.lengthSquared = function () {
  940. return (this.x * this.x + this.y * this.y);
  941. };
  942. // Methods
  943. /**
  944. * Normalize the vector.
  945. * Returns the updated Vector2.
  946. */
  947. Vector2.prototype.normalize = function () {
  948. var len = this.length();
  949. if (len === 0)
  950. return this;
  951. var num = 1.0 / len;
  952. this.x *= num;
  953. this.y *= num;
  954. return this;
  955. };
  956. /**
  957. * Returns a new Vector2 copied from the Vector2.
  958. */
  959. Vector2.prototype.clone = function () {
  960. return new Vector2(this.x, this.y);
  961. };
  962. // Statics
  963. /**
  964. * Returns a new Vector2(0, 0)
  965. */
  966. Vector2.Zero = function () {
  967. return new Vector2(0, 0);
  968. };
  969. /**
  970. * Returns a new Vector2(1, 1)
  971. */
  972. Vector2.One = function () {
  973. return new Vector2(1, 1);
  974. };
  975. /**
  976. * Returns a new Vector2 set from the passed index element of the passed array.
  977. */
  978. Vector2.FromArray = function (array, offset) {
  979. if (offset === void 0) { offset = 0; }
  980. return new Vector2(array[offset], array[offset + 1]);
  981. };
  982. /**
  983. * Sets "result" from the passed index element of the passed array.
  984. */
  985. Vector2.FromArrayToRef = function (array, offset, result) {
  986. result.x = array[offset];
  987. result.y = array[offset + 1];
  988. };
  989. /**
  990. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  991. */
  992. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  993. var squared = amount * amount;
  994. var cubed = amount * squared;
  995. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  996. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  997. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  998. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  999. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1000. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1001. return new Vector2(x, y);
  1002. };
  1003. /**
  1004. * 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".
  1005. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1006. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1007. */
  1008. Vector2.Clamp = function (value, min, max) {
  1009. var x = value.x;
  1010. x = (x > max.x) ? max.x : x;
  1011. x = (x < min.x) ? min.x : x;
  1012. var y = value.y;
  1013. y = (y > max.y) ? max.y : y;
  1014. y = (y < min.y) ? min.y : y;
  1015. return new Vector2(x, y);
  1016. };
  1017. /**
  1018. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1019. */
  1020. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1021. var squared = amount * amount;
  1022. var cubed = amount * squared;
  1023. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1024. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1025. var part3 = (cubed - (2.0 * squared)) + amount;
  1026. var part4 = cubed - squared;
  1027. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1028. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1029. return new Vector2(x, y);
  1030. };
  1031. /**
  1032. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1033. */
  1034. Vector2.Lerp = function (start, end, amount) {
  1035. var x = start.x + ((end.x - start.x) * amount);
  1036. var y = start.y + ((end.y - start.y) * amount);
  1037. return new Vector2(x, y);
  1038. };
  1039. /**
  1040. * Returns the dot product (float) of the vector "left" and the vector "right".
  1041. */
  1042. Vector2.Dot = function (left, right) {
  1043. return left.x * right.x + left.y * right.y;
  1044. };
  1045. /**
  1046. * Returns a new Vector2 equal to the normalized passed vector.
  1047. */
  1048. Vector2.Normalize = function (vector) {
  1049. var newVector = vector.clone();
  1050. newVector.normalize();
  1051. return newVector;
  1052. };
  1053. /**
  1054. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1055. */
  1056. Vector2.Minimize = function (left, right) {
  1057. var x = (left.x < right.x) ? left.x : right.x;
  1058. var y = (left.y < right.y) ? left.y : right.y;
  1059. return new Vector2(x, y);
  1060. };
  1061. /**
  1062. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1063. */
  1064. Vector2.Maximize = function (left, right) {
  1065. var x = (left.x > right.x) ? left.x : right.x;
  1066. var y = (left.y > right.y) ? left.y : right.y;
  1067. return new Vector2(x, y);
  1068. };
  1069. /**
  1070. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1071. */
  1072. Vector2.Transform = function (vector, transformation) {
  1073. var r = Vector2.Zero();
  1074. Vector2.TransformToRef(vector, transformation, r);
  1075. return r;
  1076. };
  1077. /**
  1078. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1079. */
  1080. Vector2.TransformToRef = function (vector, transformation, result) {
  1081. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1082. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1083. result.x = x;
  1084. result.y = y;
  1085. };
  1086. /**
  1087. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1088. */
  1089. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1090. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1091. var sign = a < 0 ? -1 : 1;
  1092. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1093. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1094. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1095. };
  1096. /**
  1097. * Returns the distance (float) between the vectors "value1" and "value2".
  1098. */
  1099. Vector2.Distance = function (value1, value2) {
  1100. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1101. };
  1102. /**
  1103. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1104. */
  1105. Vector2.DistanceSquared = function (value1, value2) {
  1106. var x = value1.x - value2.x;
  1107. var y = value1.y - value2.y;
  1108. return (x * x) + (y * y);
  1109. };
  1110. /**
  1111. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1112. */
  1113. Vector2.Center = function (value1, value2) {
  1114. var center = value1.add(value2);
  1115. center.scaleInPlace(0.5);
  1116. return center;
  1117. };
  1118. /**
  1119. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1120. */
  1121. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1122. var l2 = Vector2.DistanceSquared(segA, segB);
  1123. if (l2 === 0.0) {
  1124. return Vector2.Distance(p, segA);
  1125. }
  1126. var v = segB.subtract(segA);
  1127. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1128. var proj = segA.add(v.multiplyByFloats(t, t));
  1129. return Vector2.Distance(p, proj);
  1130. };
  1131. return Vector2;
  1132. }());
  1133. BABYLON.Vector2 = Vector2;
  1134. var Vector3 = (function () {
  1135. /**
  1136. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1137. * A Vector3 is the main object used in 3D geometry.
  1138. * It can represent etiher the coordinates of a point the space, either a direction.
  1139. */
  1140. function Vector3(x, y, z) {
  1141. this.x = x;
  1142. this.y = y;
  1143. this.z = z;
  1144. }
  1145. /**
  1146. * Returns a string with the Vector3 coordinates.
  1147. */
  1148. Vector3.prototype.toString = function () {
  1149. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1150. };
  1151. /**
  1152. * Returns the string "Vector3"
  1153. */
  1154. Vector3.prototype.getClassName = function () {
  1155. return "Vector3";
  1156. };
  1157. /**
  1158. * Returns the Vector hash code.
  1159. */
  1160. Vector3.prototype.getHashCode = function () {
  1161. var hash = this.x || 0;
  1162. hash = (hash * 397) ^ (this.y || 0);
  1163. hash = (hash * 397) ^ (this.z || 0);
  1164. return hash;
  1165. };
  1166. // Operators
  1167. /**
  1168. * Returns a new array with three elements : the coordinates the Vector3.
  1169. */
  1170. Vector3.prototype.asArray = function () {
  1171. var result = [];
  1172. this.toArray(result, 0);
  1173. return result;
  1174. };
  1175. /**
  1176. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1177. * Returns the Vector3.
  1178. */
  1179. Vector3.prototype.toArray = function (array, index) {
  1180. if (index === void 0) { index = 0; }
  1181. array[index] = this.x;
  1182. array[index + 1] = this.y;
  1183. array[index + 2] = this.z;
  1184. return this;
  1185. };
  1186. /**
  1187. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1188. */
  1189. Vector3.prototype.toQuaternion = function () {
  1190. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1191. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1192. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1193. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1194. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1195. var cosy = Math.cos(this.y * 0.5);
  1196. var siny = Math.sin(this.y * 0.5);
  1197. result.x = coszMinusx * siny;
  1198. result.y = -sinzMinusx * siny;
  1199. result.z = sinxPlusz * cosy;
  1200. result.w = cosxPlusz * cosy;
  1201. return result;
  1202. };
  1203. /**
  1204. * Adds the passed vector to the current Vector3.
  1205. * Returns the updated Vector3.
  1206. */
  1207. Vector3.prototype.addInPlace = function (otherVector) {
  1208. this.x += otherVector.x;
  1209. this.y += otherVector.y;
  1210. this.z += otherVector.z;
  1211. return this;
  1212. };
  1213. /**
  1214. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1215. */
  1216. Vector3.prototype.add = function (otherVector) {
  1217. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1218. };
  1219. /**
  1220. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1221. * Returns the current Vector3.
  1222. */
  1223. Vector3.prototype.addToRef = function (otherVector, result) {
  1224. result.x = this.x + otherVector.x;
  1225. result.y = this.y + otherVector.y;
  1226. result.z = this.z + otherVector.z;
  1227. return this;
  1228. };
  1229. /**
  1230. * Subtract the passed vector from the current Vector3.
  1231. * Returns the updated Vector3.
  1232. */
  1233. Vector3.prototype.subtractInPlace = function (otherVector) {
  1234. this.x -= otherVector.x;
  1235. this.y -= otherVector.y;
  1236. this.z -= otherVector.z;
  1237. return this;
  1238. };
  1239. /**
  1240. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1241. */
  1242. Vector3.prototype.subtract = function (otherVector) {
  1243. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1244. };
  1245. /**
  1246. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1247. * Returns the current Vector3.
  1248. */
  1249. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1250. result.x = this.x - otherVector.x;
  1251. result.y = this.y - otherVector.y;
  1252. result.z = this.z - otherVector.z;
  1253. return this;
  1254. };
  1255. /**
  1256. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1257. */
  1258. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1259. return new Vector3(this.x - x, this.y - y, this.z - z);
  1260. };
  1261. /**
  1262. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1263. * Returns the current Vector3.
  1264. */
  1265. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1266. result.x = this.x - x;
  1267. result.y = this.y - y;
  1268. result.z = this.z - z;
  1269. return this;
  1270. };
  1271. /**
  1272. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1273. */
  1274. Vector3.prototype.negate = function () {
  1275. return new Vector3(-this.x, -this.y, -this.z);
  1276. };
  1277. /**
  1278. * Multiplies the Vector3 coordinates by the float "scale".
  1279. * Returns the updated Vector3.
  1280. */
  1281. Vector3.prototype.scaleInPlace = function (scale) {
  1282. this.x *= scale;
  1283. this.y *= scale;
  1284. this.z *= scale;
  1285. return this;
  1286. };
  1287. /**
  1288. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1289. */
  1290. Vector3.prototype.scale = function (scale) {
  1291. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1292. };
  1293. /**
  1294. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1295. * Returns the current Vector3.
  1296. */
  1297. Vector3.prototype.scaleToRef = function (scale, result) {
  1298. result.x = this.x * scale;
  1299. result.y = this.y * scale;
  1300. result.z = this.z * scale;
  1301. return this;
  1302. };
  1303. /**
  1304. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1305. */
  1306. Vector3.prototype.equals = function (otherVector) {
  1307. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1308. };
  1309. /**
  1310. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1311. */
  1312. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1313. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1314. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1315. };
  1316. /**
  1317. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1318. */
  1319. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1320. return this.x === x && this.y === y && this.z === z;
  1321. };
  1322. /**
  1323. * Muliplies the current Vector3 coordinates by the passed ones.
  1324. * Returns the updated Vector3.
  1325. */
  1326. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1327. this.x *= otherVector.x;
  1328. this.y *= otherVector.y;
  1329. this.z *= otherVector.z;
  1330. return this;
  1331. };
  1332. /**
  1333. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1334. */
  1335. Vector3.prototype.multiply = function (otherVector) {
  1336. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1337. };
  1338. /**
  1339. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1340. * Returns the current Vector3.
  1341. */
  1342. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1343. result.x = this.x * otherVector.x;
  1344. result.y = this.y * otherVector.y;
  1345. result.z = this.z * otherVector.z;
  1346. return this;
  1347. };
  1348. /**
  1349. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1350. */
  1351. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1352. return new Vector3(this.x * x, this.y * y, this.z * z);
  1353. };
  1354. /**
  1355. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1356. */
  1357. Vector3.prototype.divide = function (otherVector) {
  1358. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1359. };
  1360. /**
  1361. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1362. * Returns the current Vector3.
  1363. */
  1364. Vector3.prototype.divideToRef = function (otherVector, result) {
  1365. result.x = this.x / otherVector.x;
  1366. result.y = this.y / otherVector.y;
  1367. result.z = this.z / otherVector.z;
  1368. return this;
  1369. };
  1370. /**
  1371. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1372. * Returns the updated Vector3.
  1373. */
  1374. Vector3.prototype.MinimizeInPlace = function (other) {
  1375. if (other.x < this.x)
  1376. this.x = other.x;
  1377. if (other.y < this.y)
  1378. this.y = other.y;
  1379. if (other.z < this.z)
  1380. this.z = other.z;
  1381. return this;
  1382. };
  1383. /**
  1384. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1385. * Returns the updated Vector3.
  1386. */
  1387. Vector3.prototype.MaximizeInPlace = function (other) {
  1388. if (other.x > this.x)
  1389. this.x = other.x;
  1390. if (other.y > this.y)
  1391. this.y = other.y;
  1392. if (other.z > this.z)
  1393. this.z = other.z;
  1394. return this;
  1395. };
  1396. // Properties
  1397. /**
  1398. * Returns the length of the Vector3 (float).
  1399. */
  1400. Vector3.prototype.length = function () {
  1401. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1402. };
  1403. /**
  1404. * Returns the squared length of the Vector3 (float).
  1405. */
  1406. Vector3.prototype.lengthSquared = function () {
  1407. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1408. };
  1409. // Methods
  1410. /**
  1411. * Normalize the current Vector3.
  1412. * Returns the updated Vector3.
  1413. */
  1414. Vector3.prototype.normalize = function () {
  1415. var len = this.length();
  1416. if (len === 0 || len === 1.0)
  1417. return this;
  1418. var num = 1.0 / len;
  1419. this.x *= num;
  1420. this.y *= num;
  1421. this.z *= num;
  1422. return this;
  1423. };
  1424. /**
  1425. * Returns a new Vector3 copied from the current Vector3.
  1426. */
  1427. Vector3.prototype.clone = function () {
  1428. return new Vector3(this.x, this.y, this.z);
  1429. };
  1430. /**
  1431. * Copies the passed vector coordinates to the current Vector3 ones.
  1432. * Returns the updated Vector3.
  1433. */
  1434. Vector3.prototype.copyFrom = function (source) {
  1435. this.x = source.x;
  1436. this.y = source.y;
  1437. this.z = source.z;
  1438. return this;
  1439. };
  1440. /**
  1441. * Copies the passed floats to the current Vector3 coordinates.
  1442. * Returns the updated Vector3.
  1443. */
  1444. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1445. this.x = x;
  1446. this.y = y;
  1447. this.z = z;
  1448. return this;
  1449. };
  1450. /**
  1451. * Copies the passed floats to the current Vector3 coordinates.
  1452. * Returns the updated Vector3.
  1453. */
  1454. Vector3.prototype.set = function (x, y, z) {
  1455. return this.copyFromFloats(x, y, z);
  1456. };
  1457. // Statics
  1458. /**
  1459. *
  1460. */
  1461. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1462. var d0 = Vector3.Dot(vector0, axis) - size;
  1463. var d1 = Vector3.Dot(vector1, axis) - size;
  1464. var s = d0 / (d0 - d1);
  1465. return s;
  1466. };
  1467. /**
  1468. * Returns a new Vector3 set from the index "offset" of the passed array.
  1469. */
  1470. Vector3.FromArray = function (array, offset) {
  1471. if (!offset) {
  1472. offset = 0;
  1473. }
  1474. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1475. };
  1476. /**
  1477. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1478. * This function is deprecated. Use FromArray instead.
  1479. */
  1480. Vector3.FromFloatArray = function (array, offset) {
  1481. return Vector3.FromArray(array, offset);
  1482. };
  1483. /**
  1484. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1485. */
  1486. Vector3.FromArrayToRef = function (array, offset, result) {
  1487. result.x = array[offset];
  1488. result.y = array[offset + 1];
  1489. result.z = array[offset + 2];
  1490. };
  1491. /**
  1492. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1493. * This function is deprecated. Use FromArrayToRef instead.
  1494. */
  1495. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1496. return Vector3.FromArrayToRef(array, offset, result);
  1497. };
  1498. /**
  1499. * Sets the passed vector "result" with the passed floats.
  1500. */
  1501. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1502. result.x = x;
  1503. result.y = y;
  1504. result.z = z;
  1505. };
  1506. /**
  1507. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1508. */
  1509. Vector3.Zero = function () {
  1510. return new Vector3(0.0, 0.0, 0.0);
  1511. };
  1512. /**
  1513. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1514. */
  1515. Vector3.One = function () {
  1516. return new Vector3(1.0, 1.0, 1.0);
  1517. };
  1518. /**
  1519. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1520. */
  1521. Vector3.Up = function () {
  1522. return new Vector3(0.0, 1.0, 0.0);
  1523. };
  1524. /**
  1525. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1526. */
  1527. Vector3.Forward = function () {
  1528. return new Vector3(0.0, 0.0, 1.0);
  1529. };
  1530. /**
  1531. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1532. */
  1533. Vector3.Right = function () {
  1534. return new Vector3(1.0, 0.0, 0.0);
  1535. };
  1536. /**
  1537. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1538. */
  1539. Vector3.Left = function () {
  1540. return new Vector3(-1.0, 0.0, 0.0);
  1541. };
  1542. /**
  1543. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1544. * This method computes tranformed coordinates only, not transformed direction vectors.
  1545. */
  1546. Vector3.TransformCoordinates = function (vector, transformation) {
  1547. var result = Vector3.Zero();
  1548. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1549. return result;
  1550. };
  1551. /**
  1552. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1553. * This method computes tranformed coordinates only, not transformed direction vectors.
  1554. */
  1555. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1556. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1557. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1558. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1559. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1560. result.x = x / w;
  1561. result.y = y / w;
  1562. result.z = z / w;
  1563. };
  1564. /**
  1565. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1566. * This method computes tranformed coordinates only, not transformed direction vectors.
  1567. */
  1568. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1569. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1570. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1571. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1572. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1573. result.x = rx / rw;
  1574. result.y = ry / rw;
  1575. result.z = rz / rw;
  1576. };
  1577. /**
  1578. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1579. * This methods computes transformed normalized direction vectors only.
  1580. */
  1581. Vector3.TransformNormal = function (vector, transformation) {
  1582. var result = Vector3.Zero();
  1583. Vector3.TransformNormalToRef(vector, transformation, result);
  1584. return result;
  1585. };
  1586. /**
  1587. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1588. * This methods computes transformed normalized direction vectors only.
  1589. */
  1590. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1591. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1592. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1593. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1594. result.x = x;
  1595. result.y = y;
  1596. result.z = z;
  1597. };
  1598. /**
  1599. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1600. * This methods computes transformed normalized direction vectors only.
  1601. */
  1602. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1603. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1604. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1605. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1606. };
  1607. /**
  1608. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1609. */
  1610. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1611. var squared = amount * amount;
  1612. var cubed = amount * squared;
  1613. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1614. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1615. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1616. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1617. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1618. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1619. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1620. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1621. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1622. return new Vector3(x, y, z);
  1623. };
  1624. /**
  1625. * 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".
  1626. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1627. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1628. */
  1629. Vector3.Clamp = function (value, min, max) {
  1630. var x = value.x;
  1631. x = (x > max.x) ? max.x : x;
  1632. x = (x < min.x) ? min.x : x;
  1633. var y = value.y;
  1634. y = (y > max.y) ? max.y : y;
  1635. y = (y < min.y) ? min.y : y;
  1636. var z = value.z;
  1637. z = (z > max.z) ? max.z : z;
  1638. z = (z < min.z) ? min.z : z;
  1639. return new Vector3(x, y, z);
  1640. };
  1641. /**
  1642. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1643. */
  1644. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1645. var squared = amount * amount;
  1646. var cubed = amount * squared;
  1647. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1648. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1649. var part3 = (cubed - (2.0 * squared)) + amount;
  1650. var part4 = cubed - squared;
  1651. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1652. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1653. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1654. return new Vector3(x, y, z);
  1655. };
  1656. /**
  1657. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1658. */
  1659. Vector3.Lerp = function (start, end, amount) {
  1660. var result = new Vector3(0, 0, 0);
  1661. Vector3.LerpToRef(start, end, amount, result);
  1662. return result;
  1663. };
  1664. /**
  1665. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1666. */
  1667. Vector3.LerpToRef = function (start, end, amount, result) {
  1668. result.x = start.x + ((end.x - start.x) * amount);
  1669. result.y = start.y + ((end.y - start.y) * amount);
  1670. result.z = start.z + ((end.z - start.z) * amount);
  1671. };
  1672. /**
  1673. * Returns the dot product (float) between the vectors "left" and "right".
  1674. */
  1675. Vector3.Dot = function (left, right) {
  1676. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1677. };
  1678. /**
  1679. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1680. * The cross product is then orthogonal to both "left" and "right".
  1681. */
  1682. Vector3.Cross = function (left, right) {
  1683. var result = Vector3.Zero();
  1684. Vector3.CrossToRef(left, right, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the cross product of "left" and "right".
  1689. * The cross product is then orthogonal to both "left" and "right".
  1690. */
  1691. Vector3.CrossToRef = function (left, right, result) {
  1692. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1693. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1694. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1695. result.copyFrom(MathTmp.Vector3[0]);
  1696. };
  1697. /**
  1698. * Returns a new Vector3 as the normalization of the passed vector.
  1699. */
  1700. Vector3.Normalize = function (vector) {
  1701. var result = Vector3.Zero();
  1702. Vector3.NormalizeToRef(vector, result);
  1703. return result;
  1704. };
  1705. /**
  1706. * Sets the passed vector "result" with the normalization of the passed first vector.
  1707. */
  1708. Vector3.NormalizeToRef = function (vector, result) {
  1709. result.copyFrom(vector);
  1710. result.normalize();
  1711. };
  1712. Vector3.Project = function (vector, world, transform, viewport) {
  1713. var cw = viewport.width;
  1714. var ch = viewport.height;
  1715. var cx = viewport.x;
  1716. var cy = viewport.y;
  1717. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1718. 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);
  1719. var matrix = MathTmp.Matrix[0];
  1720. world.multiplyToRef(transform, matrix);
  1721. matrix.multiplyToRef(viewportMatrix, matrix);
  1722. return Vector3.TransformCoordinates(vector, matrix);
  1723. };
  1724. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1725. var matrix = MathTmp.Matrix[0];
  1726. world.multiplyToRef(transform, matrix);
  1727. matrix.invert();
  1728. source.x = source.x / viewportWidth * 2 - 1;
  1729. source.y = -(source.y / viewportHeight * 2 - 1);
  1730. var vector = Vector3.TransformCoordinates(source, matrix);
  1731. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1732. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1733. vector = vector.scale(1.0 / num);
  1734. }
  1735. return vector;
  1736. };
  1737. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1738. var matrix = MathTmp.Matrix[0];
  1739. world.multiplyToRef(view, matrix);
  1740. matrix.multiplyToRef(projection, matrix);
  1741. matrix.invert();
  1742. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1743. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1744. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1745. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1746. vector = vector.scale(1.0 / num);
  1747. }
  1748. return vector;
  1749. };
  1750. Vector3.Minimize = function (left, right) {
  1751. var min = left.clone();
  1752. min.MinimizeInPlace(right);
  1753. return min;
  1754. };
  1755. Vector3.Maximize = function (left, right) {
  1756. var max = left.clone();
  1757. max.MaximizeInPlace(right);
  1758. return max;
  1759. };
  1760. /**
  1761. * Returns the distance (float) between the vectors "value1" and "value2".
  1762. */
  1763. Vector3.Distance = function (value1, value2) {
  1764. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1765. };
  1766. /**
  1767. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1768. */
  1769. Vector3.DistanceSquared = function (value1, value2) {
  1770. var x = value1.x - value2.x;
  1771. var y = value1.y - value2.y;
  1772. var z = value1.z - value2.z;
  1773. return (x * x) + (y * y) + (z * z);
  1774. };
  1775. /**
  1776. * Returns a new Vector3 located at the center between "value1" and "value2".
  1777. */
  1778. Vector3.Center = function (value1, value2) {
  1779. var center = value1.add(value2);
  1780. center.scaleInPlace(0.5);
  1781. return center;
  1782. };
  1783. /**
  1784. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1785. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1786. * to something in order to rotate it from its local system to the given target system.
  1787. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1788. * Returns a new Vector3.
  1789. */
  1790. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1791. var rotation = Vector3.Zero();
  1792. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1793. return rotation;
  1794. };
  1795. /**
  1796. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1797. */
  1798. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1799. var quat = MathTmp.Quaternion[0];
  1800. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1801. quat.toEulerAnglesToRef(ref);
  1802. };
  1803. return Vector3;
  1804. }());
  1805. BABYLON.Vector3 = Vector3;
  1806. //Vector4 class created for EulerAngle class conversion to Quaternion
  1807. var Vector4 = (function () {
  1808. /**
  1809. * Creates a Vector4 object from the passed floats.
  1810. */
  1811. function Vector4(x, y, z, w) {
  1812. this.x = x;
  1813. this.y = y;
  1814. this.z = z;
  1815. this.w = w;
  1816. }
  1817. /**
  1818. * Returns the string with the Vector4 coordinates.
  1819. */
  1820. Vector4.prototype.toString = function () {
  1821. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1822. };
  1823. /**
  1824. * Returns the string "Vector4".
  1825. */
  1826. Vector4.prototype.getClassName = function () {
  1827. return "Vector4";
  1828. };
  1829. /**
  1830. * Returns the Vector4 hash code.
  1831. */
  1832. Vector4.prototype.getHashCode = function () {
  1833. var hash = this.x || 0;
  1834. hash = (hash * 397) ^ (this.y || 0);
  1835. hash = (hash * 397) ^ (this.z || 0);
  1836. hash = (hash * 397) ^ (this.w || 0);
  1837. return hash;
  1838. };
  1839. // Operators
  1840. /**
  1841. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1842. */
  1843. Vector4.prototype.asArray = function () {
  1844. var result = [];
  1845. this.toArray(result, 0);
  1846. return result;
  1847. };
  1848. /**
  1849. * Populates the passed array from the passed index with the Vector4 coordinates.
  1850. * Returns the Vector4.
  1851. */
  1852. Vector4.prototype.toArray = function (array, index) {
  1853. if (index === undefined) {
  1854. index = 0;
  1855. }
  1856. array[index] = this.x;
  1857. array[index + 1] = this.y;
  1858. array[index + 2] = this.z;
  1859. array[index + 3] = this.w;
  1860. return this;
  1861. };
  1862. /**
  1863. * Adds the passed vector to the current Vector4.
  1864. * Returns the updated Vector4.
  1865. */
  1866. Vector4.prototype.addInPlace = function (otherVector) {
  1867. this.x += otherVector.x;
  1868. this.y += otherVector.y;
  1869. this.z += otherVector.z;
  1870. this.w += otherVector.w;
  1871. return this;
  1872. };
  1873. /**
  1874. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1875. */
  1876. Vector4.prototype.add = function (otherVector) {
  1877. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1878. };
  1879. /**
  1880. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1881. * Returns the current Vector4.
  1882. */
  1883. Vector4.prototype.addToRef = function (otherVector, result) {
  1884. result.x = this.x + otherVector.x;
  1885. result.y = this.y + otherVector.y;
  1886. result.z = this.z + otherVector.z;
  1887. result.w = this.w + otherVector.w;
  1888. return this;
  1889. };
  1890. /**
  1891. * Subtract in place the passed vector from the current Vector4.
  1892. * Returns the updated Vector4.
  1893. */
  1894. Vector4.prototype.subtractInPlace = function (otherVector) {
  1895. this.x -= otherVector.x;
  1896. this.y -= otherVector.y;
  1897. this.z -= otherVector.z;
  1898. this.w -= otherVector.w;
  1899. return this;
  1900. };
  1901. /**
  1902. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1903. */
  1904. Vector4.prototype.subtract = function (otherVector) {
  1905. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1906. };
  1907. /**
  1908. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1909. * Returns the current Vector4.
  1910. */
  1911. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1912. result.x = this.x - otherVector.x;
  1913. result.y = this.y - otherVector.y;
  1914. result.z = this.z - otherVector.z;
  1915. result.w = this.w - otherVector.w;
  1916. return this;
  1917. };
  1918. /**
  1919. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1920. */
  1921. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1922. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1923. };
  1924. /**
  1925. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1926. * Returns the current Vector4.
  1927. */
  1928. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1929. result.x = this.x - x;
  1930. result.y = this.y - y;
  1931. result.z = this.z - z;
  1932. result.w = this.w - w;
  1933. return this;
  1934. };
  1935. /**
  1936. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1937. */
  1938. Vector4.prototype.negate = function () {
  1939. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1940. };
  1941. /**
  1942. * Multiplies the current Vector4 coordinates by scale (float).
  1943. * Returns the updated Vector4.
  1944. */
  1945. Vector4.prototype.scaleInPlace = function (scale) {
  1946. this.x *= scale;
  1947. this.y *= scale;
  1948. this.z *= scale;
  1949. this.w *= scale;
  1950. return this;
  1951. };
  1952. /**
  1953. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1954. */
  1955. Vector4.prototype.scale = function (scale) {
  1956. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1957. };
  1958. /**
  1959. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1960. * Returns the current Vector4.
  1961. */
  1962. Vector4.prototype.scaleToRef = function (scale, result) {
  1963. result.x = this.x * scale;
  1964. result.y = this.y * scale;
  1965. result.z = this.z * scale;
  1966. result.w = this.w * scale;
  1967. return this;
  1968. };
  1969. /**
  1970. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1971. */
  1972. Vector4.prototype.equals = function (otherVector) {
  1973. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1974. };
  1975. /**
  1976. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1977. */
  1978. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1979. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1980. return otherVector
  1981. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  1982. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  1983. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  1984. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  1985. };
  1986. /**
  1987. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1988. */
  1989. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1990. return this.x === x && this.y === y && this.z === z && this.w === w;
  1991. };
  1992. /**
  1993. * Multiplies in place the current Vector4 by the passed one.
  1994. * Returns the updated Vector4.
  1995. */
  1996. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1997. this.x *= otherVector.x;
  1998. this.y *= otherVector.y;
  1999. this.z *= otherVector.z;
  2000. this.w *= otherVector.w;
  2001. return this;
  2002. };
  2003. /**
  2004. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2005. */
  2006. Vector4.prototype.multiply = function (otherVector) {
  2007. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2008. };
  2009. /**
  2010. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2011. * Returns the current Vector4.
  2012. */
  2013. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2014. result.x = this.x * otherVector.x;
  2015. result.y = this.y * otherVector.y;
  2016. result.z = this.z * otherVector.z;
  2017. result.w = this.w * otherVector.w;
  2018. return this;
  2019. };
  2020. /**
  2021. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2022. */
  2023. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2024. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2025. };
  2026. /**
  2027. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2028. */
  2029. Vector4.prototype.divide = function (otherVector) {
  2030. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2031. };
  2032. /**
  2033. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2034. * Returns the current Vector4.
  2035. */
  2036. Vector4.prototype.divideToRef = function (otherVector, result) {
  2037. result.x = this.x / otherVector.x;
  2038. result.y = this.y / otherVector.y;
  2039. result.z = this.z / otherVector.z;
  2040. result.w = this.w / otherVector.w;
  2041. return this;
  2042. };
  2043. /**
  2044. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2045. */
  2046. Vector4.prototype.MinimizeInPlace = function (other) {
  2047. if (other.x < this.x)
  2048. this.x = other.x;
  2049. if (other.y < this.y)
  2050. this.y = other.y;
  2051. if (other.z < this.z)
  2052. this.z = other.z;
  2053. if (other.w < this.w)
  2054. this.w = other.w;
  2055. return this;
  2056. };
  2057. /**
  2058. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2059. */
  2060. Vector4.prototype.MaximizeInPlace = function (other) {
  2061. if (other.x > this.x)
  2062. this.x = other.x;
  2063. if (other.y > this.y)
  2064. this.y = other.y;
  2065. if (other.z > this.z)
  2066. this.z = other.z;
  2067. if (other.w > this.w)
  2068. this.w = other.w;
  2069. return this;
  2070. };
  2071. // Properties
  2072. /**
  2073. * Returns the Vector4 length (float).
  2074. */
  2075. Vector4.prototype.length = function () {
  2076. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2077. };
  2078. /**
  2079. * Returns the Vector4 squared length (float).
  2080. */
  2081. Vector4.prototype.lengthSquared = function () {
  2082. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2083. };
  2084. // Methods
  2085. /**
  2086. * Normalizes in place the Vector4.
  2087. * Returns the updated Vector4.
  2088. */
  2089. Vector4.prototype.normalize = function () {
  2090. var len = this.length();
  2091. if (len === 0)
  2092. return this;
  2093. var num = 1.0 / len;
  2094. this.x *= num;
  2095. this.y *= num;
  2096. this.z *= num;
  2097. this.w *= num;
  2098. return this;
  2099. };
  2100. /**
  2101. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2102. */
  2103. Vector4.prototype.toVector3 = function () {
  2104. return new Vector3(this.x, this.y, this.z);
  2105. };
  2106. /**
  2107. * Returns a new Vector4 copied from the current one.
  2108. */
  2109. Vector4.prototype.clone = function () {
  2110. return new Vector4(this.x, this.y, this.z, this.w);
  2111. };
  2112. /**
  2113. * Updates the current Vector4 with the passed one coordinates.
  2114. * Returns the updated Vector4.
  2115. */
  2116. Vector4.prototype.copyFrom = function (source) {
  2117. this.x = source.x;
  2118. this.y = source.y;
  2119. this.z = source.z;
  2120. this.w = source.w;
  2121. return this;
  2122. };
  2123. /**
  2124. * Updates the current Vector4 coordinates with the passed floats.
  2125. * Returns the updated Vector4.
  2126. */
  2127. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2128. this.x = x;
  2129. this.y = y;
  2130. this.z = z;
  2131. this.w = w;
  2132. return this;
  2133. };
  2134. /**
  2135. * Updates the current Vector4 coordinates with the passed floats.
  2136. * Returns the updated Vector4.
  2137. */
  2138. Vector4.prototype.set = function (x, y, z, w) {
  2139. return this.copyFromFloats(x, y, z, w);
  2140. };
  2141. // Statics
  2142. /**
  2143. * Returns a new Vector4 set from the starting index of the passed array.
  2144. */
  2145. Vector4.FromArray = function (array, offset) {
  2146. if (!offset) {
  2147. offset = 0;
  2148. }
  2149. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2150. };
  2151. /**
  2152. * Updates the passed vector "result" from the starting index of the passed array.
  2153. */
  2154. Vector4.FromArrayToRef = function (array, offset, result) {
  2155. result.x = array[offset];
  2156. result.y = array[offset + 1];
  2157. result.z = array[offset + 2];
  2158. result.w = array[offset + 3];
  2159. };
  2160. /**
  2161. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2162. */
  2163. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2164. Vector4.FromArrayToRef(array, offset, result);
  2165. };
  2166. /**
  2167. * Updates the passed vector "result" coordinates from the passed floats.
  2168. */
  2169. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2170. result.x = x;
  2171. result.y = y;
  2172. result.z = z;
  2173. result.w = w;
  2174. };
  2175. /**
  2176. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2177. */
  2178. Vector4.Zero = function () {
  2179. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2180. };
  2181. /**
  2182. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2183. */
  2184. Vector4.One = function () {
  2185. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2186. };
  2187. /**
  2188. * Returns a new normalized Vector4 from the passed one.
  2189. */
  2190. Vector4.Normalize = function (vector) {
  2191. var result = Vector4.Zero();
  2192. Vector4.NormalizeToRef(vector, result);
  2193. return result;
  2194. };
  2195. /**
  2196. * Updates the passed vector "result" from the normalization of the passed one.
  2197. */
  2198. Vector4.NormalizeToRef = function (vector, result) {
  2199. result.copyFrom(vector);
  2200. result.normalize();
  2201. };
  2202. Vector4.Minimize = function (left, right) {
  2203. var min = left.clone();
  2204. min.MinimizeInPlace(right);
  2205. return min;
  2206. };
  2207. Vector4.Maximize = function (left, right) {
  2208. var max = left.clone();
  2209. max.MaximizeInPlace(right);
  2210. return max;
  2211. };
  2212. /**
  2213. * Returns the distance (float) between the vectors "value1" and "value2".
  2214. */
  2215. Vector4.Distance = function (value1, value2) {
  2216. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2217. };
  2218. /**
  2219. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2220. */
  2221. Vector4.DistanceSquared = function (value1, value2) {
  2222. var x = value1.x - value2.x;
  2223. var y = value1.y - value2.y;
  2224. var z = value1.z - value2.z;
  2225. var w = value1.w - value2.w;
  2226. return (x * x) + (y * y) + (z * z) + (w * w);
  2227. };
  2228. /**
  2229. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2230. */
  2231. Vector4.Center = function (value1, value2) {
  2232. var center = value1.add(value2);
  2233. center.scaleInPlace(0.5);
  2234. return center;
  2235. };
  2236. /**
  2237. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2238. * This methods computes transformed normalized direction vectors only.
  2239. */
  2240. Vector4.TransformNormal = function (vector, transformation) {
  2241. var result = Vector4.Zero();
  2242. Vector4.TransformNormalToRef(vector, transformation, result);
  2243. return result;
  2244. };
  2245. /**
  2246. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2247. * This methods computes transformed normalized direction vectors only.
  2248. */
  2249. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2250. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2251. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2252. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2253. result.x = x;
  2254. result.y = y;
  2255. result.z = z;
  2256. result.w = vector.w;
  2257. };
  2258. /**
  2259. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2260. * This methods computes transformed normalized direction vectors only.
  2261. */
  2262. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2263. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2264. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2265. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2266. result.w = w;
  2267. };
  2268. return Vector4;
  2269. }());
  2270. BABYLON.Vector4 = Vector4;
  2271. var Size = (function () {
  2272. /**
  2273. * Creates a Size object from the passed width and height (floats).
  2274. */
  2275. function Size(width, height) {
  2276. this.width = width;
  2277. this.height = height;
  2278. }
  2279. // Returns a string with the Size width and height.
  2280. Size.prototype.toString = function () {
  2281. return "{W: " + this.width + ", H: " + this.height + "}";
  2282. };
  2283. /**
  2284. * Returns the string "Size"
  2285. */
  2286. Size.prototype.getClassName = function () {
  2287. return "Size";
  2288. };
  2289. /**
  2290. * Returns the Size hash code.
  2291. */
  2292. Size.prototype.getHashCode = function () {
  2293. var hash = this.width || 0;
  2294. hash = (hash * 397) ^ (this.height || 0);
  2295. return hash;
  2296. };
  2297. /**
  2298. * Updates the current size from the passed one.
  2299. * Returns the updated Size.
  2300. */
  2301. Size.prototype.copyFrom = function (src) {
  2302. this.width = src.width;
  2303. this.height = src.height;
  2304. };
  2305. /**
  2306. * Updates in place the current Size from the passed floats.
  2307. * Returns the updated Size.
  2308. */
  2309. Size.prototype.copyFromFloats = function (width, height) {
  2310. this.width = width;
  2311. this.height = height;
  2312. return this;
  2313. };
  2314. /**
  2315. * Updates in place the current Size from the passed floats.
  2316. * Returns the updated Size.
  2317. */
  2318. Size.prototype.set = function (width, height) {
  2319. return this.copyFromFloats(width, height);
  2320. };
  2321. /**
  2322. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2323. */
  2324. Size.prototype.multiplyByFloats = function (w, h) {
  2325. return new Size(this.width * w, this.height * h);
  2326. };
  2327. /**
  2328. * Returns a new Size copied from the passed one.
  2329. */
  2330. Size.prototype.clone = function () {
  2331. return new Size(this.width, this.height);
  2332. };
  2333. /**
  2334. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2335. */
  2336. Size.prototype.equals = function (other) {
  2337. if (!other) {
  2338. return false;
  2339. }
  2340. return (this.width === other.width) && (this.height === other.height);
  2341. };
  2342. Object.defineProperty(Size.prototype, "surface", {
  2343. /**
  2344. * Returns the surface of the Size : width * height (float).
  2345. */
  2346. get: function () {
  2347. return this.width * this.height;
  2348. },
  2349. enumerable: true,
  2350. configurable: true
  2351. });
  2352. /**
  2353. * Returns a new Size set to (0.0, 0.0)
  2354. */
  2355. Size.Zero = function () {
  2356. return new Size(0.0, 0.0);
  2357. };
  2358. /**
  2359. * Returns a new Size set as the addition result of the current Size and the passed one.
  2360. */
  2361. Size.prototype.add = function (otherSize) {
  2362. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2363. return r;
  2364. };
  2365. /**
  2366. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2367. */
  2368. Size.prototype.subtract = function (otherSize) {
  2369. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2370. return r;
  2371. };
  2372. /**
  2373. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2374. */
  2375. Size.Lerp = function (start, end, amount) {
  2376. var w = start.width + ((end.width - start.width) * amount);
  2377. var h = start.height + ((end.height - start.height) * amount);
  2378. return new Size(w, h);
  2379. };
  2380. return Size;
  2381. }());
  2382. BABYLON.Size = Size;
  2383. var Quaternion = (function () {
  2384. /**
  2385. * Creates a new Quaternion from the passed floats.
  2386. */
  2387. function Quaternion(x, y, z, w) {
  2388. if (x === void 0) { x = 0.0; }
  2389. if (y === void 0) { y = 0.0; }
  2390. if (z === void 0) { z = 0.0; }
  2391. if (w === void 0) { w = 1.0; }
  2392. this.x = x;
  2393. this.y = y;
  2394. this.z = z;
  2395. this.w = w;
  2396. }
  2397. /**
  2398. * Returns a string with the Quaternion coordinates.
  2399. */
  2400. Quaternion.prototype.toString = function () {
  2401. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2402. };
  2403. /**
  2404. * Returns the string "Quaternion".
  2405. */
  2406. Quaternion.prototype.getClassName = function () {
  2407. return "Quaternion";
  2408. };
  2409. /**
  2410. * Returns the Quaternion hash code.
  2411. */
  2412. Quaternion.prototype.getHashCode = function () {
  2413. var hash = this.x || 0;
  2414. hash = (hash * 397) ^ (this.y || 0);
  2415. hash = (hash * 397) ^ (this.z || 0);
  2416. hash = (hash * 397) ^ (this.w || 0);
  2417. return hash;
  2418. };
  2419. /**
  2420. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2421. */
  2422. Quaternion.prototype.asArray = function () {
  2423. return [this.x, this.y, this.z, this.w];
  2424. };
  2425. /**
  2426. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2427. */
  2428. Quaternion.prototype.equals = function (otherQuaternion) {
  2429. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2430. };
  2431. /**
  2432. * Returns a new Quaternion copied from the current one.
  2433. */
  2434. Quaternion.prototype.clone = function () {
  2435. return new Quaternion(this.x, this.y, this.z, this.w);
  2436. };
  2437. /**
  2438. * Updates the current Quaternion from the passed one coordinates.
  2439. * Returns the updated Quaterion.
  2440. */
  2441. Quaternion.prototype.copyFrom = function (other) {
  2442. this.x = other.x;
  2443. this.y = other.y;
  2444. this.z = other.z;
  2445. this.w = other.w;
  2446. return this;
  2447. };
  2448. /**
  2449. * Updates the current Quaternion from the passed float coordinates.
  2450. * Returns the updated Quaterion.
  2451. */
  2452. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2453. this.x = x;
  2454. this.y = y;
  2455. this.z = z;
  2456. this.w = w;
  2457. return this;
  2458. };
  2459. /**
  2460. * Updates the current Quaternion from the passed float coordinates.
  2461. * Returns the updated Quaterion.
  2462. */
  2463. Quaternion.prototype.set = function (x, y, z, w) {
  2464. return this.copyFromFloats(x, y, z, w);
  2465. };
  2466. /**
  2467. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2468. */
  2469. Quaternion.prototype.add = function (other) {
  2470. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2471. };
  2472. /**
  2473. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2474. */
  2475. Quaternion.prototype.subtract = function (other) {
  2476. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2477. };
  2478. /**
  2479. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2480. */
  2481. Quaternion.prototype.scale = function (value) {
  2482. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2483. };
  2484. /**
  2485. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2486. */
  2487. Quaternion.prototype.multiply = function (q1) {
  2488. var result = new Quaternion(0, 0, 0, 1.0);
  2489. this.multiplyToRef(q1, result);
  2490. return result;
  2491. };
  2492. /**
  2493. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2494. * Returns the current Quaternion.
  2495. */
  2496. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2497. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2498. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2499. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2500. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2501. result.copyFromFloats(x, y, z, w);
  2502. return this;
  2503. };
  2504. /**
  2505. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2506. * Returns the updated Quaternion.
  2507. */
  2508. Quaternion.prototype.multiplyInPlace = function (q1) {
  2509. this.multiplyToRef(q1, this);
  2510. return this;
  2511. };
  2512. /**
  2513. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2514. * Returns the current Quaternion.
  2515. */
  2516. Quaternion.prototype.conjugateToRef = function (ref) {
  2517. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2518. return this;
  2519. };
  2520. /**
  2521. * Conjugates in place the current Quaternion.
  2522. * Returns the updated Quaternion.
  2523. */
  2524. Quaternion.prototype.conjugateInPlace = function () {
  2525. this.x *= -1;
  2526. this.y *= -1;
  2527. this.z *= -1;
  2528. return this;
  2529. };
  2530. /**
  2531. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2532. */
  2533. Quaternion.prototype.conjugate = function () {
  2534. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2535. return result;
  2536. };
  2537. /**
  2538. * Returns the Quaternion length (float).
  2539. */
  2540. Quaternion.prototype.length = function () {
  2541. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2542. };
  2543. /**
  2544. * Normalize in place the current Quaternion.
  2545. * Returns the updated Quaternion.
  2546. */
  2547. Quaternion.prototype.normalize = function () {
  2548. var length = 1.0 / this.length();
  2549. this.x *= length;
  2550. this.y *= length;
  2551. this.z *= length;
  2552. this.w *= length;
  2553. return this;
  2554. };
  2555. /**
  2556. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2557. */
  2558. Quaternion.prototype.toEulerAngles = function (order) {
  2559. if (order === void 0) { order = "YZX"; }
  2560. var result = Vector3.Zero();
  2561. this.toEulerAnglesToRef(result, order);
  2562. return result;
  2563. };
  2564. /**
  2565. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2566. * Returns the current Quaternion.
  2567. */
  2568. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2569. if (order === void 0) { order = "YZX"; }
  2570. var qz = this.z;
  2571. var qx = this.x;
  2572. var qy = this.y;
  2573. var qw = this.w;
  2574. var sqw = qw * qw;
  2575. var sqz = qz * qz;
  2576. var sqx = qx * qx;
  2577. var sqy = qy * qy;
  2578. var zAxisY = qy * qz - qx * qw;
  2579. var limit = .4999999;
  2580. if (zAxisY < -limit) {
  2581. result.y = 2 * Math.atan2(qy, qw);
  2582. result.x = Math.PI / 2;
  2583. result.z = 0;
  2584. }
  2585. else if (zAxisY > limit) {
  2586. result.y = 2 * Math.atan2(qy, qw);
  2587. result.x = -Math.PI / 2;
  2588. result.z = 0;
  2589. }
  2590. else {
  2591. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2592. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2593. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2594. }
  2595. return this;
  2596. };
  2597. /**
  2598. * Updates the passed rotation matrix with the current Quaternion values.
  2599. * Returns the current Quaternion.
  2600. */
  2601. Quaternion.prototype.toRotationMatrix = function (result) {
  2602. var xx = this.x * this.x;
  2603. var yy = this.y * this.y;
  2604. var zz = this.z * this.z;
  2605. var xy = this.x * this.y;
  2606. var zw = this.z * this.w;
  2607. var zx = this.z * this.x;
  2608. var yw = this.y * this.w;
  2609. var yz = this.y * this.z;
  2610. var xw = this.x * this.w;
  2611. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2612. result.m[1] = 2.0 * (xy + zw);
  2613. result.m[2] = 2.0 * (zx - yw);
  2614. result.m[3] = 0;
  2615. result.m[4] = 2.0 * (xy - zw);
  2616. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2617. result.m[6] = 2.0 * (yz + xw);
  2618. result.m[7] = 0;
  2619. result.m[8] = 2.0 * (zx + yw);
  2620. result.m[9] = 2.0 * (yz - xw);
  2621. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2622. result.m[11] = 0;
  2623. result.m[12] = 0;
  2624. result.m[13] = 0;
  2625. result.m[14] = 0;
  2626. result.m[15] = 1.0;
  2627. result._markAsUpdated();
  2628. return this;
  2629. };
  2630. /**
  2631. * Updates the current Quaternion from the passed rotation matrix values.
  2632. * Returns the updated Quaternion.
  2633. */
  2634. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2635. Quaternion.FromRotationMatrixToRef(matrix, this);
  2636. return this;
  2637. };
  2638. // Statics
  2639. /**
  2640. * Returns a new Quaternion set from the passed rotation matrix values.
  2641. */
  2642. Quaternion.FromRotationMatrix = function (matrix) {
  2643. var result = new Quaternion();
  2644. Quaternion.FromRotationMatrixToRef(matrix, result);
  2645. return result;
  2646. };
  2647. /**
  2648. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2649. */
  2650. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2651. var data = matrix.m;
  2652. var m11 = data[0], m12 = data[4], m13 = data[8];
  2653. var m21 = data[1], m22 = data[5], m23 = data[9];
  2654. var m31 = data[2], m32 = data[6], m33 = data[10];
  2655. var trace = m11 + m22 + m33;
  2656. var s;
  2657. if (trace > 0) {
  2658. s = 0.5 / Math.sqrt(trace + 1.0);
  2659. result.w = 0.25 / s;
  2660. result.x = (m32 - m23) * s;
  2661. result.y = (m13 - m31) * s;
  2662. result.z = (m21 - m12) * s;
  2663. }
  2664. else if (m11 > m22 && m11 > m33) {
  2665. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2666. result.w = (m32 - m23) / s;
  2667. result.x = 0.25 * s;
  2668. result.y = (m12 + m21) / s;
  2669. result.z = (m13 + m31) / s;
  2670. }
  2671. else if (m22 > m33) {
  2672. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2673. result.w = (m13 - m31) / s;
  2674. result.x = (m12 + m21) / s;
  2675. result.y = 0.25 * s;
  2676. result.z = (m23 + m32) / s;
  2677. }
  2678. else {
  2679. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2680. result.w = (m21 - m12) / s;
  2681. result.x = (m13 + m31) / s;
  2682. result.y = (m23 + m32) / s;
  2683. result.z = 0.25 * s;
  2684. }
  2685. };
  2686. /**
  2687. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2688. */
  2689. Quaternion.Zero = function () {
  2690. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2691. };
  2692. /**
  2693. * Returns a new Quaternion as the inverted current Quaternion.
  2694. */
  2695. Quaternion.Inverse = function (q) {
  2696. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2697. };
  2698. /**
  2699. * Returns the identity Quaternion.
  2700. */
  2701. Quaternion.Identity = function () {
  2702. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2703. };
  2704. Quaternion.IsIdentity = function (quaternion) {
  2705. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2706. };
  2707. /**
  2708. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2709. */
  2710. Quaternion.RotationAxis = function (axis, angle) {
  2711. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2712. };
  2713. /**
  2714. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2715. */
  2716. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2717. var sin = Math.sin(angle / 2);
  2718. axis.normalize();
  2719. result.w = Math.cos(angle / 2);
  2720. result.x = axis.x * sin;
  2721. result.y = axis.y * sin;
  2722. result.z = axis.z * sin;
  2723. return result;
  2724. };
  2725. /**
  2726. * Retuns a new Quaternion set from the starting index of the passed array.
  2727. */
  2728. Quaternion.FromArray = function (array, offset) {
  2729. if (!offset) {
  2730. offset = 0;
  2731. }
  2732. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2733. };
  2734. /**
  2735. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2736. */
  2737. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2738. var q = new Quaternion();
  2739. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2740. return q;
  2741. };
  2742. /**
  2743. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2744. */
  2745. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2746. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2747. var halfRoll = roll * 0.5;
  2748. var halfPitch = pitch * 0.5;
  2749. var halfYaw = yaw * 0.5;
  2750. var sinRoll = Math.sin(halfRoll);
  2751. var cosRoll = Math.cos(halfRoll);
  2752. var sinPitch = Math.sin(halfPitch);
  2753. var cosPitch = Math.cos(halfPitch);
  2754. var sinYaw = Math.sin(halfYaw);
  2755. var cosYaw = Math.cos(halfYaw);
  2756. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2757. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2758. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2759. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2760. };
  2761. /**
  2762. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2763. */
  2764. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2765. var result = new Quaternion();
  2766. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2767. return result;
  2768. };
  2769. /**
  2770. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2771. */
  2772. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2773. // Produces a quaternion from Euler angles in the z-x-z orientation
  2774. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2775. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2776. var halfBeta = beta * 0.5;
  2777. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2778. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2779. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2780. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2781. };
  2782. /**
  2783. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2784. * cf to Vector3.RotationFromAxis() documentation.
  2785. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2786. */
  2787. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2788. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2789. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2790. return quat;
  2791. };
  2792. /**
  2793. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2794. * cf to Vector3.RotationFromAxis() documentation.
  2795. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2796. */
  2797. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2798. var rotMat = MathTmp.Matrix[0];
  2799. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2800. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2801. };
  2802. Quaternion.Slerp = function (left, right, amount) {
  2803. var result = Quaternion.Identity();
  2804. Quaternion.SlerpToRef(left, right, amount, result);
  2805. return result;
  2806. };
  2807. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2808. var num2;
  2809. var num3;
  2810. var num = amount;
  2811. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2812. var flag = false;
  2813. if (num4 < 0) {
  2814. flag = true;
  2815. num4 = -num4;
  2816. }
  2817. if (num4 > 0.999999) {
  2818. num3 = 1 - num;
  2819. num2 = flag ? -num : num;
  2820. }
  2821. else {
  2822. var num5 = Math.acos(num4);
  2823. var num6 = (1.0 / Math.sin(num5));
  2824. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2825. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2826. }
  2827. result.x = (num3 * left.x) + (num2 * right.x);
  2828. result.y = (num3 * left.y) + (num2 * right.y);
  2829. result.z = (num3 * left.z) + (num2 * right.z);
  2830. result.w = (num3 * left.w) + (num2 * right.w);
  2831. };
  2832. /**
  2833. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2834. */
  2835. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2836. var squared = amount * amount;
  2837. var cubed = amount * squared;
  2838. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2839. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2840. var part3 = (cubed - (2.0 * squared)) + amount;
  2841. var part4 = cubed - squared;
  2842. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2843. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2844. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2845. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2846. return new Quaternion(x, y, z, w);
  2847. };
  2848. return Quaternion;
  2849. }());
  2850. BABYLON.Quaternion = Quaternion;
  2851. var Matrix = (function () {
  2852. function Matrix() {
  2853. this._isIdentity = false;
  2854. this._isIdentityDirty = true;
  2855. this.m = new Float32Array(16);
  2856. this._markAsUpdated();
  2857. }
  2858. Matrix.prototype._markAsUpdated = function () {
  2859. this.updateFlag = Matrix._updateFlagSeed++;
  2860. this._isIdentityDirty = true;
  2861. };
  2862. // Properties
  2863. /**
  2864. * Boolean : True is the matrix is the identity matrix
  2865. */
  2866. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2867. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2868. if (this._isIdentityDirty) {
  2869. this._isIdentityDirty = false;
  2870. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2871. this._isIdentity = false;
  2872. }
  2873. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2874. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2875. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2876. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2877. this._isIdentity = false;
  2878. }
  2879. else {
  2880. this._isIdentity = true;
  2881. }
  2882. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2883. this._isIdentity = false;
  2884. }
  2885. }
  2886. return this._isIdentity;
  2887. };
  2888. /**
  2889. * Returns the matrix determinant (float).
  2890. */
  2891. Matrix.prototype.determinant = function () {
  2892. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2893. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2894. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2895. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2896. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2897. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2898. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2899. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2900. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2901. };
  2902. // Methods
  2903. /**
  2904. * Returns the matrix underlying array.
  2905. */
  2906. Matrix.prototype.toArray = function () {
  2907. return this.m;
  2908. };
  2909. /**
  2910. * Returns the matrix underlying array.
  2911. */
  2912. Matrix.prototype.asArray = function () {
  2913. return this.toArray();
  2914. };
  2915. /**
  2916. * Inverts in place the Matrix.
  2917. * Returns the Matrix inverted.
  2918. */
  2919. Matrix.prototype.invert = function () {
  2920. this.invertToRef(this);
  2921. return this;
  2922. };
  2923. /**
  2924. * Sets all the matrix elements to zero.
  2925. * Returns the Matrix.
  2926. */
  2927. Matrix.prototype.reset = function () {
  2928. for (var index = 0; index < 16; index++) {
  2929. this.m[index] = 0.0;
  2930. }
  2931. this._markAsUpdated();
  2932. return this;
  2933. };
  2934. /**
  2935. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2936. */
  2937. Matrix.prototype.add = function (other) {
  2938. var result = new Matrix();
  2939. this.addToRef(other, result);
  2940. return result;
  2941. };
  2942. /**
  2943. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2944. * Returns the Matrix.
  2945. */
  2946. Matrix.prototype.addToRef = function (other, result) {
  2947. for (var index = 0; index < 16; index++) {
  2948. result.m[index] = this.m[index] + other.m[index];
  2949. }
  2950. result._markAsUpdated();
  2951. return this;
  2952. };
  2953. /**
  2954. * Adds in place the passed matrix to the current Matrix.
  2955. * Returns the updated Matrix.
  2956. */
  2957. Matrix.prototype.addToSelf = function (other) {
  2958. for (var index = 0; index < 16; index++) {
  2959. this.m[index] += other.m[index];
  2960. }
  2961. this._markAsUpdated();
  2962. return this;
  2963. };
  2964. /**
  2965. * Sets the passed matrix with the current inverted Matrix.
  2966. * Returns the unmodified current Matrix.
  2967. */
  2968. Matrix.prototype.invertToRef = function (other) {
  2969. var l1 = this.m[0];
  2970. var l2 = this.m[1];
  2971. var l3 = this.m[2];
  2972. var l4 = this.m[3];
  2973. var l5 = this.m[4];
  2974. var l6 = this.m[5];
  2975. var l7 = this.m[6];
  2976. var l8 = this.m[7];
  2977. var l9 = this.m[8];
  2978. var l10 = this.m[9];
  2979. var l11 = this.m[10];
  2980. var l12 = this.m[11];
  2981. var l13 = this.m[12];
  2982. var l14 = this.m[13];
  2983. var l15 = this.m[14];
  2984. var l16 = this.m[15];
  2985. var l17 = (l11 * l16) - (l12 * l15);
  2986. var l18 = (l10 * l16) - (l12 * l14);
  2987. var l19 = (l10 * l15) - (l11 * l14);
  2988. var l20 = (l9 * l16) - (l12 * l13);
  2989. var l21 = (l9 * l15) - (l11 * l13);
  2990. var l22 = (l9 * l14) - (l10 * l13);
  2991. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2992. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2993. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2994. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2995. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2996. var l28 = (l7 * l16) - (l8 * l15);
  2997. var l29 = (l6 * l16) - (l8 * l14);
  2998. var l30 = (l6 * l15) - (l7 * l14);
  2999. var l31 = (l5 * l16) - (l8 * l13);
  3000. var l32 = (l5 * l15) - (l7 * l13);
  3001. var l33 = (l5 * l14) - (l6 * l13);
  3002. var l34 = (l7 * l12) - (l8 * l11);
  3003. var l35 = (l6 * l12) - (l8 * l10);
  3004. var l36 = (l6 * l11) - (l7 * l10);
  3005. var l37 = (l5 * l12) - (l8 * l9);
  3006. var l38 = (l5 * l11) - (l7 * l9);
  3007. var l39 = (l5 * l10) - (l6 * l9);
  3008. other.m[0] = l23 * l27;
  3009. other.m[4] = l24 * l27;
  3010. other.m[8] = l25 * l27;
  3011. other.m[12] = l26 * l27;
  3012. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3013. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3014. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3015. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3016. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3017. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3018. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3019. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3020. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3021. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3022. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3023. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3024. other._markAsUpdated();
  3025. return this;
  3026. };
  3027. /**
  3028. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3029. * Returns the updated Matrix.
  3030. */
  3031. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3032. this.m[12] = x;
  3033. this.m[13] = y;
  3034. this.m[14] = z;
  3035. this._markAsUpdated();
  3036. return this;
  3037. };
  3038. /**
  3039. * Inserts the translation vector in the current Matrix.
  3040. * Returns the updated Matrix.
  3041. */
  3042. Matrix.prototype.setTranslation = function (vector3) {
  3043. this.m[12] = vector3.x;
  3044. this.m[13] = vector3.y;
  3045. this.m[14] = vector3.z;
  3046. this._markAsUpdated();
  3047. return this;
  3048. };
  3049. /**
  3050. * Returns a new Vector3 as the extracted translation from the Matrix.
  3051. */
  3052. Matrix.prototype.getTranslation = function () {
  3053. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3054. };
  3055. /**
  3056. * Fill a Vector3 with the extracted translation from the Matrix.
  3057. */
  3058. Matrix.prototype.getTranslationToRef = function (result) {
  3059. result.x = this.m[12];
  3060. result.y = this.m[13];
  3061. result.z = this.m[14];
  3062. return this;
  3063. };
  3064. /**
  3065. * Remove rotation and scaling part from the Matrix.
  3066. * Returns the updated Matrix.
  3067. */
  3068. Matrix.prototype.removeRotationAndScaling = function () {
  3069. this.setRowFromFloats(0, 1, 0, 0, 0);
  3070. this.setRowFromFloats(1, 0, 1, 0, 0);
  3071. this.setRowFromFloats(2, 0, 0, 1, 0);
  3072. return this;
  3073. };
  3074. /**
  3075. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3076. */
  3077. Matrix.prototype.multiply = function (other) {
  3078. var result = new Matrix();
  3079. this.multiplyToRef(other, result);
  3080. return result;
  3081. };
  3082. /**
  3083. * Updates the current Matrix from the passed one values.
  3084. * Returns the updated Matrix.
  3085. */
  3086. Matrix.prototype.copyFrom = function (other) {
  3087. for (var index = 0; index < 16; index++) {
  3088. this.m[index] = other.m[index];
  3089. }
  3090. this._markAsUpdated();
  3091. return this;
  3092. };
  3093. /**
  3094. * Populates the passed array from the starting index with the Matrix values.
  3095. * Returns the Matrix.
  3096. */
  3097. Matrix.prototype.copyToArray = function (array, offset) {
  3098. if (offset === void 0) { offset = 0; }
  3099. for (var index = 0; index < 16; index++) {
  3100. array[offset + index] = this.m[index];
  3101. }
  3102. return this;
  3103. };
  3104. /**
  3105. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3106. */
  3107. Matrix.prototype.multiplyToRef = function (other, result) {
  3108. this.multiplyToArray(other, result.m, 0);
  3109. result._markAsUpdated();
  3110. return this;
  3111. };
  3112. /**
  3113. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3114. */
  3115. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3116. var tm0 = this.m[0];
  3117. var tm1 = this.m[1];
  3118. var tm2 = this.m[2];
  3119. var tm3 = this.m[3];
  3120. var tm4 = this.m[4];
  3121. var tm5 = this.m[5];
  3122. var tm6 = this.m[6];
  3123. var tm7 = this.m[7];
  3124. var tm8 = this.m[8];
  3125. var tm9 = this.m[9];
  3126. var tm10 = this.m[10];
  3127. var tm11 = this.m[11];
  3128. var tm12 = this.m[12];
  3129. var tm13 = this.m[13];
  3130. var tm14 = this.m[14];
  3131. var tm15 = this.m[15];
  3132. var om0 = other.m[0];
  3133. var om1 = other.m[1];
  3134. var om2 = other.m[2];
  3135. var om3 = other.m[3];
  3136. var om4 = other.m[4];
  3137. var om5 = other.m[5];
  3138. var om6 = other.m[6];
  3139. var om7 = other.m[7];
  3140. var om8 = other.m[8];
  3141. var om9 = other.m[9];
  3142. var om10 = other.m[10];
  3143. var om11 = other.m[11];
  3144. var om12 = other.m[12];
  3145. var om13 = other.m[13];
  3146. var om14 = other.m[14];
  3147. var om15 = other.m[15];
  3148. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3149. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3150. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3151. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3152. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3153. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3154. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3155. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3156. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3157. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3158. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3159. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3160. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3161. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3162. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3163. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3164. return this;
  3165. };
  3166. /**
  3167. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3168. */
  3169. Matrix.prototype.equals = function (value) {
  3170. return value &&
  3171. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3172. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3173. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3174. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3175. };
  3176. /**
  3177. * Returns a new Matrix from the current Matrix.
  3178. */
  3179. Matrix.prototype.clone = function () {
  3180. 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]);
  3181. };
  3182. /**
  3183. * Returns the string "Matrix"
  3184. */
  3185. Matrix.prototype.getClassName = function () {
  3186. return "Matrix";
  3187. };
  3188. /**
  3189. * Returns the Matrix hash code.
  3190. */
  3191. Matrix.prototype.getHashCode = function () {
  3192. var hash = this.m[0] || 0;
  3193. for (var i = 1; i < 16; i++) {
  3194. hash = (hash * 397) ^ (this.m[i] || 0);
  3195. }
  3196. return hash;
  3197. };
  3198. /**
  3199. * Decomposes the current Matrix into :
  3200. * - a scale vector3 passed as a reference to update,
  3201. * - a rotation quaternion passed as a reference to update,
  3202. * - a translation vector3 passed as a reference to update.
  3203. * Returns the boolean `true`.
  3204. */
  3205. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3206. translation.x = this.m[12];
  3207. translation.y = this.m[13];
  3208. translation.z = this.m[14];
  3209. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3210. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3211. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3212. if (this.determinant() <= 0) {
  3213. scale.y *= -1;
  3214. }
  3215. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3216. rotation.x = 0;
  3217. rotation.y = 0;
  3218. rotation.z = 0;
  3219. rotation.w = 1;
  3220. return false;
  3221. }
  3222. 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]);
  3223. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3224. return true;
  3225. };
  3226. /**
  3227. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3228. */
  3229. Matrix.prototype.getRotationMatrix = function () {
  3230. var result = Matrix.Identity();
  3231. this.getRotationMatrixToRef(result);
  3232. return result;
  3233. };
  3234. /**
  3235. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3236. * Returns the current Matrix.
  3237. */
  3238. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3239. var m = this.m;
  3240. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3241. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3242. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3243. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3244. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3245. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3246. 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);
  3247. return this;
  3248. };
  3249. // Statics
  3250. /**
  3251. * Returns a new Matrix set from the starting index of the passed array.
  3252. */
  3253. Matrix.FromArray = function (array, offset) {
  3254. var result = new Matrix();
  3255. if (!offset) {
  3256. offset = 0;
  3257. }
  3258. Matrix.FromArrayToRef(array, offset, result);
  3259. return result;
  3260. };
  3261. /**
  3262. * Sets the passed "result" matrix from the starting index of the passed array.
  3263. */
  3264. Matrix.FromArrayToRef = function (array, offset, result) {
  3265. for (var index = 0; index < 16; index++) {
  3266. result.m[index] = array[index + offset];
  3267. }
  3268. result._markAsUpdated();
  3269. };
  3270. /**
  3271. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3272. */
  3273. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3274. for (var index = 0; index < 16; index++) {
  3275. result.m[index] = array[index + offset] * scale;
  3276. }
  3277. result._markAsUpdated();
  3278. };
  3279. /**
  3280. * Sets the passed matrix "result" with the 16 passed floats.
  3281. */
  3282. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3283. result.m[0] = initialM11;
  3284. result.m[1] = initialM12;
  3285. result.m[2] = initialM13;
  3286. result.m[3] = initialM14;
  3287. result.m[4] = initialM21;
  3288. result.m[5] = initialM22;
  3289. result.m[6] = initialM23;
  3290. result.m[7] = initialM24;
  3291. result.m[8] = initialM31;
  3292. result.m[9] = initialM32;
  3293. result.m[10] = initialM33;
  3294. result.m[11] = initialM34;
  3295. result.m[12] = initialM41;
  3296. result.m[13] = initialM42;
  3297. result.m[14] = initialM43;
  3298. result.m[15] = initialM44;
  3299. result._markAsUpdated();
  3300. };
  3301. /**
  3302. * Returns the index-th row of the current matrix as a new Vector4.
  3303. */
  3304. Matrix.prototype.getRow = function (index) {
  3305. if (index < 0 || index > 3) {
  3306. return null;
  3307. }
  3308. var i = index * 4;
  3309. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3310. };
  3311. /**
  3312. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3313. * Returns the updated Matrix.
  3314. */
  3315. Matrix.prototype.setRow = function (index, row) {
  3316. if (index < 0 || index > 3) {
  3317. return this;
  3318. }
  3319. var i = index * 4;
  3320. this.m[i + 0] = row.x;
  3321. this.m[i + 1] = row.y;
  3322. this.m[i + 2] = row.z;
  3323. this.m[i + 3] = row.w;
  3324. this._markAsUpdated();
  3325. return this;
  3326. };
  3327. /**
  3328. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3329. * Returns the updated Matrix.
  3330. */
  3331. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3332. if (index < 0 || index > 3) {
  3333. return this;
  3334. }
  3335. var i = index * 4;
  3336. this.m[i + 0] = x;
  3337. this.m[i + 1] = y;
  3338. this.m[i + 2] = z;
  3339. this.m[i + 3] = w;
  3340. this._markAsUpdated();
  3341. return this;
  3342. };
  3343. /**
  3344. * Returns a new Matrix set from the 16 passed floats.
  3345. */
  3346. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3347. var result = new Matrix();
  3348. result.m[0] = initialM11;
  3349. result.m[1] = initialM12;
  3350. result.m[2] = initialM13;
  3351. result.m[3] = initialM14;
  3352. result.m[4] = initialM21;
  3353. result.m[5] = initialM22;
  3354. result.m[6] = initialM23;
  3355. result.m[7] = initialM24;
  3356. result.m[8] = initialM31;
  3357. result.m[9] = initialM32;
  3358. result.m[10] = initialM33;
  3359. result.m[11] = initialM34;
  3360. result.m[12] = initialM41;
  3361. result.m[13] = initialM42;
  3362. result.m[14] = initialM43;
  3363. result.m[15] = initialM44;
  3364. return result;
  3365. };
  3366. /**
  3367. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3368. */
  3369. Matrix.Compose = function (scale, rotation, translation) {
  3370. var result = Matrix.Identity();
  3371. Matrix.ComposeToRef(scale, rotation, translation, result);
  3372. return result;
  3373. };
  3374. /**
  3375. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3376. */
  3377. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3378. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3379. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3380. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3381. result.setTranslation(translation);
  3382. };
  3383. /**
  3384. * Returns a new indentity Matrix.
  3385. */
  3386. Matrix.Identity = function () {
  3387. 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);
  3388. };
  3389. /**
  3390. * Sets the passed "result" as an identity matrix.
  3391. */
  3392. Matrix.IdentityToRef = function (result) {
  3393. 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);
  3394. };
  3395. /**
  3396. * Returns a new zero Matrix.
  3397. */
  3398. Matrix.Zero = function () {
  3399. 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);
  3400. };
  3401. /**
  3402. * Returns a new rotation matrix for "angle" radians around the X axis.
  3403. */
  3404. Matrix.RotationX = function (angle) {
  3405. var result = new Matrix();
  3406. Matrix.RotationXToRef(angle, result);
  3407. return result;
  3408. };
  3409. /**
  3410. * Returns a new Matrix as the passed inverted one.
  3411. */
  3412. Matrix.Invert = function (source) {
  3413. var result = new Matrix();
  3414. source.invertToRef(result);
  3415. return result;
  3416. };
  3417. /**
  3418. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3419. */
  3420. Matrix.RotationXToRef = function (angle, result) {
  3421. var s = Math.sin(angle);
  3422. var c = Math.cos(angle);
  3423. result.m[0] = 1.0;
  3424. result.m[15] = 1.0;
  3425. result.m[5] = c;
  3426. result.m[10] = c;
  3427. result.m[9] = -s;
  3428. result.m[6] = s;
  3429. result.m[1] = 0.0;
  3430. result.m[2] = 0.0;
  3431. result.m[3] = 0.0;
  3432. result.m[4] = 0.0;
  3433. result.m[7] = 0.0;
  3434. result.m[8] = 0.0;
  3435. result.m[11] = 0.0;
  3436. result.m[12] = 0.0;
  3437. result.m[13] = 0.0;
  3438. result.m[14] = 0.0;
  3439. result._markAsUpdated();
  3440. };
  3441. /**
  3442. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3443. */
  3444. Matrix.RotationY = function (angle) {
  3445. var result = new Matrix();
  3446. Matrix.RotationYToRef(angle, result);
  3447. return result;
  3448. };
  3449. /**
  3450. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3451. */
  3452. Matrix.RotationYToRef = function (angle, result) {
  3453. var s = Math.sin(angle);
  3454. var c = Math.cos(angle);
  3455. result.m[5] = 1.0;
  3456. result.m[15] = 1.0;
  3457. result.m[0] = c;
  3458. result.m[2] = -s;
  3459. result.m[8] = s;
  3460. result.m[10] = c;
  3461. result.m[1] = 0.0;
  3462. result.m[3] = 0.0;
  3463. result.m[4] = 0.0;
  3464. result.m[6] = 0.0;
  3465. result.m[7] = 0.0;
  3466. result.m[9] = 0.0;
  3467. result.m[11] = 0.0;
  3468. result.m[12] = 0.0;
  3469. result.m[13] = 0.0;
  3470. result.m[14] = 0.0;
  3471. result._markAsUpdated();
  3472. };
  3473. /**
  3474. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3475. */
  3476. Matrix.RotationZ = function (angle) {
  3477. var result = new Matrix();
  3478. Matrix.RotationZToRef(angle, result);
  3479. return result;
  3480. };
  3481. /**
  3482. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3483. */
  3484. Matrix.RotationZToRef = function (angle, result) {
  3485. var s = Math.sin(angle);
  3486. var c = Math.cos(angle);
  3487. result.m[10] = 1.0;
  3488. result.m[15] = 1.0;
  3489. result.m[0] = c;
  3490. result.m[1] = s;
  3491. result.m[4] = -s;
  3492. result.m[5] = c;
  3493. result.m[2] = 0.0;
  3494. result.m[3] = 0.0;
  3495. result.m[6] = 0.0;
  3496. result.m[7] = 0.0;
  3497. result.m[8] = 0.0;
  3498. result.m[9] = 0.0;
  3499. result.m[11] = 0.0;
  3500. result.m[12] = 0.0;
  3501. result.m[13] = 0.0;
  3502. result.m[14] = 0.0;
  3503. result._markAsUpdated();
  3504. };
  3505. /**
  3506. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3507. */
  3508. Matrix.RotationAxis = function (axis, angle) {
  3509. var result = Matrix.Zero();
  3510. Matrix.RotationAxisToRef(axis, angle, result);
  3511. return result;
  3512. };
  3513. /**
  3514. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3515. */
  3516. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3517. var s = Math.sin(-angle);
  3518. var c = Math.cos(-angle);
  3519. var c1 = 1 - c;
  3520. axis.normalize();
  3521. result.m[0] = (axis.x * axis.x) * c1 + c;
  3522. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3523. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3524. result.m[3] = 0.0;
  3525. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3526. result.m[5] = (axis.y * axis.y) * c1 + c;
  3527. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3528. result.m[7] = 0.0;
  3529. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3530. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3531. result.m[10] = (axis.z * axis.z) * c1 + c;
  3532. result.m[11] = 0.0;
  3533. result.m[15] = 1.0;
  3534. result._markAsUpdated();
  3535. };
  3536. /**
  3537. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3538. */
  3539. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3540. var result = new Matrix();
  3541. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3542. return result;
  3543. };
  3544. /**
  3545. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3546. */
  3547. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3548. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3549. this._tempQuaternion.toRotationMatrix(result);
  3550. };
  3551. /**
  3552. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3553. */
  3554. Matrix.Scaling = function (x, y, z) {
  3555. var result = Matrix.Zero();
  3556. Matrix.ScalingToRef(x, y, z, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3561. */
  3562. Matrix.ScalingToRef = function (x, y, z, result) {
  3563. result.m[0] = x;
  3564. result.m[1] = 0.0;
  3565. result.m[2] = 0.0;
  3566. result.m[3] = 0.0;
  3567. result.m[4] = 0.0;
  3568. result.m[5] = y;
  3569. result.m[6] = 0.0;
  3570. result.m[7] = 0.0;
  3571. result.m[8] = 0.0;
  3572. result.m[9] = 0.0;
  3573. result.m[10] = z;
  3574. result.m[11] = 0.0;
  3575. result.m[12] = 0.0;
  3576. result.m[13] = 0.0;
  3577. result.m[14] = 0.0;
  3578. result.m[15] = 1.0;
  3579. result._markAsUpdated();
  3580. };
  3581. /**
  3582. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3583. */
  3584. Matrix.Translation = function (x, y, z) {
  3585. var result = Matrix.Identity();
  3586. Matrix.TranslationToRef(x, y, z, result);
  3587. return result;
  3588. };
  3589. /**
  3590. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3591. */
  3592. Matrix.TranslationToRef = function (x, y, z, result) {
  3593. 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);
  3594. };
  3595. /**
  3596. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3597. */
  3598. Matrix.Lerp = function (startValue, endValue, gradient) {
  3599. var result = Matrix.Zero();
  3600. for (var index = 0; index < 16; index++) {
  3601. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3602. }
  3603. result._markAsUpdated();
  3604. return result;
  3605. };
  3606. /**
  3607. * Returns a new Matrix whose values are computed by :
  3608. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3609. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3610. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3611. */
  3612. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3613. var startScale = new Vector3(0, 0, 0);
  3614. var startRotation = new Quaternion();
  3615. var startTranslation = new Vector3(0, 0, 0);
  3616. startValue.decompose(startScale, startRotation, startTranslation);
  3617. var endScale = new Vector3(0, 0, 0);
  3618. var endRotation = new Quaternion();
  3619. var endTranslation = new Vector3(0, 0, 0);
  3620. endValue.decompose(endScale, endRotation, endTranslation);
  3621. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3622. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3623. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3624. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3625. };
  3626. /**
  3627. * 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".
  3628. * This methods works for a Left-Handed system.
  3629. */
  3630. Matrix.LookAtLH = function (eye, target, up) {
  3631. var result = Matrix.Zero();
  3632. Matrix.LookAtLHToRef(eye, target, up, result);
  3633. return result;
  3634. };
  3635. /**
  3636. * 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".
  3637. * This methods works for a Left-Handed system.
  3638. */
  3639. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3640. // Z axis
  3641. target.subtractToRef(eye, this._zAxis);
  3642. this._zAxis.normalize();
  3643. // X axis
  3644. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3645. if (this._xAxis.lengthSquared() === 0) {
  3646. this._xAxis.x = 1.0;
  3647. }
  3648. else {
  3649. this._xAxis.normalize();
  3650. }
  3651. // Y axis
  3652. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3653. this._yAxis.normalize();
  3654. // Eye angles
  3655. var ex = -Vector3.Dot(this._xAxis, eye);
  3656. var ey = -Vector3.Dot(this._yAxis, eye);
  3657. var ez = -Vector3.Dot(this._zAxis, eye);
  3658. 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);
  3659. };
  3660. /**
  3661. * 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".
  3662. * This methods works for a Right-Handed system.
  3663. */
  3664. Matrix.LookAtRH = function (eye, target, up) {
  3665. var result = Matrix.Zero();
  3666. Matrix.LookAtRHToRef(eye, target, up, result);
  3667. return result;
  3668. };
  3669. /**
  3670. * 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".
  3671. * This methods works for a Left-Handed system.
  3672. */
  3673. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3674. // Z axis
  3675. eye.subtractToRef(target, this._zAxis);
  3676. this._zAxis.normalize();
  3677. // X axis
  3678. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3679. if (this._xAxis.lengthSquared() === 0) {
  3680. this._xAxis.x = 1.0;
  3681. }
  3682. else {
  3683. this._xAxis.normalize();
  3684. }
  3685. // Y axis
  3686. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3687. this._yAxis.normalize();
  3688. // Eye angles
  3689. var ex = -Vector3.Dot(this._xAxis, eye);
  3690. var ey = -Vector3.Dot(this._yAxis, eye);
  3691. var ez = -Vector3.Dot(this._zAxis, eye);
  3692. 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);
  3693. };
  3694. /**
  3695. * 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.
  3696. */
  3697. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3698. var matrix = Matrix.Zero();
  3699. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3700. return matrix;
  3701. };
  3702. /**
  3703. * 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.
  3704. */
  3705. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3706. var n = znear;
  3707. var f = zfar;
  3708. var a = 2.0 / width;
  3709. var b = 2.0 / height;
  3710. var c = 2.0 / (f - n);
  3711. var d = -(f + n) / (f - n);
  3712. 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);
  3713. };
  3714. /**
  3715. * 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.
  3716. */
  3717. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3718. var matrix = Matrix.Zero();
  3719. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3720. return matrix;
  3721. };
  3722. /**
  3723. * 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.
  3724. */
  3725. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3726. var n = znear;
  3727. var f = zfar;
  3728. var a = 2.0 / (right - left);
  3729. var b = 2.0 / (top - bottom);
  3730. var c = 2.0 / (f - n);
  3731. var d = -(f + n) / (f - n);
  3732. var i0 = (left + right) / (left - right);
  3733. var i1 = (top + bottom) / (bottom - top);
  3734. 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);
  3735. };
  3736. /**
  3737. * 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.
  3738. */
  3739. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3740. var matrix = Matrix.Zero();
  3741. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3742. return matrix;
  3743. };
  3744. /**
  3745. * 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.
  3746. */
  3747. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3748. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3749. result.m[10] *= -1.0;
  3750. };
  3751. /**
  3752. * 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.
  3753. */
  3754. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3755. var matrix = Matrix.Zero();
  3756. var n = znear;
  3757. var f = zfar;
  3758. var a = 2.0 * n / width;
  3759. var b = 2.0 * n / height;
  3760. var c = (f + n) / (f - n);
  3761. var d = -2.0 * f * n / (f - n);
  3762. 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);
  3763. return matrix;
  3764. };
  3765. /**
  3766. * 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.
  3767. */
  3768. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3769. var matrix = Matrix.Zero();
  3770. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3771. return matrix;
  3772. };
  3773. /**
  3774. * 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.
  3775. */
  3776. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3777. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3778. var n = znear;
  3779. var f = zfar;
  3780. var t = 1.0 / (Math.tan(fov * 0.5));
  3781. var a = isVerticalFovFixed ? (t / aspect) : t;
  3782. var b = isVerticalFovFixed ? t : (t * aspect);
  3783. var c = (f + n) / (f - n);
  3784. var d = -2.0 * f * n / (f - n);
  3785. 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);
  3786. };
  3787. /**
  3788. * 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.
  3789. */
  3790. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3791. var matrix = Matrix.Zero();
  3792. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3793. return matrix;
  3794. };
  3795. /**
  3796. * 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.
  3797. */
  3798. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3799. //alternatively this could be expressed as:
  3800. // m = PerspectiveFovLHToRef
  3801. // m[10] *= -1.0;
  3802. // m[11] *= -1.0;
  3803. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3804. var n = znear;
  3805. var f = zfar;
  3806. var t = 1.0 / (Math.tan(fov * 0.5));
  3807. var a = isVerticalFovFixed ? (t / aspect) : t;
  3808. var b = isVerticalFovFixed ? t : (t * aspect);
  3809. var c = -(f + n) / (f - n);
  3810. var d = -2 * f * n / (f - n);
  3811. 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);
  3812. };
  3813. /**
  3814. * 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.
  3815. */
  3816. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3817. if (rightHanded === void 0) { rightHanded = false; }
  3818. var rightHandedFactor = rightHanded ? -1 : 1;
  3819. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3820. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3821. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3822. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3823. var xScale = 2.0 / (leftTan + rightTan);
  3824. var yScale = 2.0 / (upTan + downTan);
  3825. result.m[0] = xScale;
  3826. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3827. result.m[5] = yScale;
  3828. result.m[6] = result.m[7] = 0.0;
  3829. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3830. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3831. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3832. result.m[10] = -zfar / (znear - zfar);
  3833. result.m[11] = 1.0 * rightHandedFactor;
  3834. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3835. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3836. // result.m[14] = (znear * zfar) / (znear - zfar);
  3837. result._markAsUpdated();
  3838. };
  3839. /**
  3840. * Returns the final transformation matrix : world * view * projection * viewport
  3841. */
  3842. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3843. var cw = viewport.width;
  3844. var ch = viewport.height;
  3845. var cx = viewport.x;
  3846. var cy = viewport.y;
  3847. 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);
  3848. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3849. };
  3850. /**
  3851. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3852. */
  3853. Matrix.GetAsMatrix2x2 = function (matrix) {
  3854. return new Float32Array([
  3855. matrix.m[0], matrix.m[1],
  3856. matrix.m[4], matrix.m[5]
  3857. ]);
  3858. };
  3859. /**
  3860. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3861. */
  3862. Matrix.GetAsMatrix3x3 = function (matrix) {
  3863. return new Float32Array([
  3864. matrix.m[0], matrix.m[1], matrix.m[2],
  3865. matrix.m[4], matrix.m[5], matrix.m[6],
  3866. matrix.m[8], matrix.m[9], matrix.m[10]
  3867. ]);
  3868. };
  3869. /**
  3870. * Compute the transpose of the passed Matrix.
  3871. * Returns a new Matrix.
  3872. */
  3873. Matrix.Transpose = function (matrix) {
  3874. var result = new Matrix();
  3875. result.m[0] = matrix.m[0];
  3876. result.m[1] = matrix.m[4];
  3877. result.m[2] = matrix.m[8];
  3878. result.m[3] = matrix.m[12];
  3879. result.m[4] = matrix.m[1];
  3880. result.m[5] = matrix.m[5];
  3881. result.m[6] = matrix.m[9];
  3882. result.m[7] = matrix.m[13];
  3883. result.m[8] = matrix.m[2];
  3884. result.m[9] = matrix.m[6];
  3885. result.m[10] = matrix.m[10];
  3886. result.m[11] = matrix.m[14];
  3887. result.m[12] = matrix.m[3];
  3888. result.m[13] = matrix.m[7];
  3889. result.m[14] = matrix.m[11];
  3890. result.m[15] = matrix.m[15];
  3891. return result;
  3892. };
  3893. /**
  3894. * Returns a new Matrix as the reflection matrix across the passed plane.
  3895. */
  3896. Matrix.Reflection = function (plane) {
  3897. var matrix = new Matrix();
  3898. Matrix.ReflectionToRef(plane, matrix);
  3899. return matrix;
  3900. };
  3901. /**
  3902. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3903. */
  3904. Matrix.ReflectionToRef = function (plane, result) {
  3905. plane.normalize();
  3906. var x = plane.normal.x;
  3907. var y = plane.normal.y;
  3908. var z = plane.normal.z;
  3909. var temp = -2 * x;
  3910. var temp2 = -2 * y;
  3911. var temp3 = -2 * z;
  3912. result.m[0] = (temp * x) + 1;
  3913. result.m[1] = temp2 * x;
  3914. result.m[2] = temp3 * x;
  3915. result.m[3] = 0.0;
  3916. result.m[4] = temp * y;
  3917. result.m[5] = (temp2 * y) + 1;
  3918. result.m[6] = temp3 * y;
  3919. result.m[7] = 0.0;
  3920. result.m[8] = temp * z;
  3921. result.m[9] = temp2 * z;
  3922. result.m[10] = (temp3 * z) + 1;
  3923. result.m[11] = 0.0;
  3924. result.m[12] = temp * plane.d;
  3925. result.m[13] = temp2 * plane.d;
  3926. result.m[14] = temp3 * plane.d;
  3927. result.m[15] = 1.0;
  3928. result._markAsUpdated();
  3929. };
  3930. /**
  3931. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3932. */
  3933. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3934. result.m[0] = xaxis.x;
  3935. result.m[1] = xaxis.y;
  3936. result.m[2] = xaxis.z;
  3937. result.m[3] = 0.0;
  3938. result.m[4] = yaxis.x;
  3939. result.m[5] = yaxis.y;
  3940. result.m[6] = yaxis.z;
  3941. result.m[7] = 0.0;
  3942. result.m[8] = zaxis.x;
  3943. result.m[9] = zaxis.y;
  3944. result.m[10] = zaxis.z;
  3945. result.m[11] = 0.0;
  3946. result.m[12] = 0.0;
  3947. result.m[13] = 0.0;
  3948. result.m[14] = 0.0;
  3949. result.m[15] = 1.0;
  3950. result._markAsUpdated();
  3951. };
  3952. /**
  3953. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3954. */
  3955. Matrix.FromQuaternionToRef = function (quat, result) {
  3956. var xx = quat.x * quat.x;
  3957. var yy = quat.y * quat.y;
  3958. var zz = quat.z * quat.z;
  3959. var xy = quat.x * quat.y;
  3960. var zw = quat.z * quat.w;
  3961. var zx = quat.z * quat.x;
  3962. var yw = quat.y * quat.w;
  3963. var yz = quat.y * quat.z;
  3964. var xw = quat.x * quat.w;
  3965. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3966. result.m[1] = 2.0 * (xy + zw);
  3967. result.m[2] = 2.0 * (zx - yw);
  3968. result.m[3] = 0.0;
  3969. result.m[4] = 2.0 * (xy - zw);
  3970. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3971. result.m[6] = 2.0 * (yz + xw);
  3972. result.m[7] = 0.0;
  3973. result.m[8] = 2.0 * (zx + yw);
  3974. result.m[9] = 2.0 * (yz - xw);
  3975. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3976. result.m[11] = 0.0;
  3977. result.m[12] = 0.0;
  3978. result.m[13] = 0.0;
  3979. result.m[14] = 0.0;
  3980. result.m[15] = 1.0;
  3981. result._markAsUpdated();
  3982. };
  3983. Matrix._tempQuaternion = new Quaternion();
  3984. Matrix._xAxis = Vector3.Zero();
  3985. Matrix._yAxis = Vector3.Zero();
  3986. Matrix._zAxis = Vector3.Zero();
  3987. Matrix._updateFlagSeed = 0;
  3988. return Matrix;
  3989. }());
  3990. BABYLON.Matrix = Matrix;
  3991. var Plane = (function () {
  3992. /**
  3993. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3994. */
  3995. function Plane(a, b, c, d) {
  3996. this.normal = new Vector3(a, b, c);
  3997. this.d = d;
  3998. }
  3999. /**
  4000. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4001. */
  4002. Plane.prototype.asArray = function () {
  4003. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4004. };
  4005. // Methods
  4006. /**
  4007. * Returns a new plane copied from the current Plane.
  4008. */
  4009. Plane.prototype.clone = function () {
  4010. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4011. };
  4012. /**
  4013. * Returns the string "Plane".
  4014. */
  4015. Plane.prototype.getClassName = function () {
  4016. return "Plane";
  4017. };
  4018. /**
  4019. * Returns the Plane hash code.
  4020. */
  4021. Plane.prototype.getHashCode = function () {
  4022. var hash = this.normal.getHashCode();
  4023. hash = (hash * 397) ^ (this.d || 0);
  4024. return hash;
  4025. };
  4026. /**
  4027. * Normalize the current Plane in place.
  4028. * Returns the updated Plane.
  4029. */
  4030. Plane.prototype.normalize = function () {
  4031. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4032. var magnitude = 0.0;
  4033. if (norm !== 0) {
  4034. magnitude = 1.0 / norm;
  4035. }
  4036. this.normal.x *= magnitude;
  4037. this.normal.y *= magnitude;
  4038. this.normal.z *= magnitude;
  4039. this.d *= magnitude;
  4040. return this;
  4041. };
  4042. /**
  4043. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4044. */
  4045. Plane.prototype.transform = function (transformation) {
  4046. var transposedMatrix = Matrix.Transpose(transformation);
  4047. var x = this.normal.x;
  4048. var y = this.normal.y;
  4049. var z = this.normal.z;
  4050. var d = this.d;
  4051. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4052. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4053. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4054. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4055. return new Plane(normalX, normalY, normalZ, finalD);
  4056. };
  4057. /**
  4058. * Returns the dot product (float) of the point coordinates and the plane normal.
  4059. */
  4060. Plane.prototype.dotCoordinate = function (point) {
  4061. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4062. };
  4063. /**
  4064. * Updates the current Plane from the plane defined by the three passed points.
  4065. * Returns the updated Plane.
  4066. */
  4067. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4068. var x1 = point2.x - point1.x;
  4069. var y1 = point2.y - point1.y;
  4070. var z1 = point2.z - point1.z;
  4071. var x2 = point3.x - point1.x;
  4072. var y2 = point3.y - point1.y;
  4073. var z2 = point3.z - point1.z;
  4074. var yz = (y1 * z2) - (z1 * y2);
  4075. var xz = (z1 * x2) - (x1 * z2);
  4076. var xy = (x1 * y2) - (y1 * x2);
  4077. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4078. var invPyth;
  4079. if (pyth !== 0) {
  4080. invPyth = 1.0 / pyth;
  4081. }
  4082. else {
  4083. invPyth = 0.0;
  4084. }
  4085. this.normal.x = yz * invPyth;
  4086. this.normal.y = xz * invPyth;
  4087. this.normal.z = xy * invPyth;
  4088. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4089. return this;
  4090. };
  4091. /**
  4092. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4093. */
  4094. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4095. var dot = Vector3.Dot(this.normal, direction);
  4096. return (dot <= epsilon);
  4097. };
  4098. /**
  4099. * Returns the signed distance (float) from the passed point to the Plane.
  4100. */
  4101. Plane.prototype.signedDistanceTo = function (point) {
  4102. return Vector3.Dot(point, this.normal) + this.d;
  4103. };
  4104. // Statics
  4105. /**
  4106. * Returns a new Plane from the passed array.
  4107. */
  4108. Plane.FromArray = function (array) {
  4109. return new Plane(array[0], array[1], array[2], array[3]);
  4110. };
  4111. /**
  4112. * Returns a new Plane defined by the three passed points.
  4113. */
  4114. Plane.FromPoints = function (point1, point2, point3) {
  4115. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4116. result.copyFromPoints(point1, point2, point3);
  4117. return result;
  4118. };
  4119. /**
  4120. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4121. * Note : the vector "normal" is updated because normalized.
  4122. */
  4123. Plane.FromPositionAndNormal = function (origin, normal) {
  4124. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4125. normal.normalize();
  4126. result.normal = normal;
  4127. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4128. return result;
  4129. };
  4130. /**
  4131. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4132. */
  4133. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4134. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4135. return Vector3.Dot(point, normal) + d;
  4136. };
  4137. return Plane;
  4138. }());
  4139. BABYLON.Plane = Plane;
  4140. var Viewport = (function () {
  4141. /**
  4142. * Creates a Viewport object located at (x, y) and sized (width, height).
  4143. */
  4144. function Viewport(x, y, width, height) {
  4145. this.x = x;
  4146. this.y = y;
  4147. this.width = width;
  4148. this.height = height;
  4149. }
  4150. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4151. if (renderWidthOrEngine.getRenderWidth) {
  4152. var engine = renderWidthOrEngine;
  4153. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4154. }
  4155. var renderWidth = renderWidthOrEngine;
  4156. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4157. };
  4158. /**
  4159. * Returns a new Viewport copied from the current one.
  4160. */
  4161. Viewport.prototype.clone = function () {
  4162. return new Viewport(this.x, this.y, this.width, this.height);
  4163. };
  4164. return Viewport;
  4165. }());
  4166. BABYLON.Viewport = Viewport;
  4167. var Frustum = (function () {
  4168. function Frustum() {
  4169. }
  4170. /**
  4171. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4172. */
  4173. Frustum.GetPlanes = function (transform) {
  4174. var frustumPlanes = [];
  4175. for (var index = 0; index < 6; index++) {
  4176. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4177. }
  4178. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4179. return frustumPlanes;
  4180. };
  4181. /**
  4182. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4183. */
  4184. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4185. // Near
  4186. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4187. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4188. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4189. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4190. frustumPlanes[0].normalize();
  4191. // Far
  4192. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4193. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4194. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4195. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4196. frustumPlanes[1].normalize();
  4197. // Left
  4198. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4199. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4200. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4201. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4202. frustumPlanes[2].normalize();
  4203. // Right
  4204. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4205. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4206. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4207. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4208. frustumPlanes[3].normalize();
  4209. // Top
  4210. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4211. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4212. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4213. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4214. frustumPlanes[4].normalize();
  4215. // Bottom
  4216. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4217. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4218. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4219. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4220. frustumPlanes[5].normalize();
  4221. };
  4222. return Frustum;
  4223. }());
  4224. BABYLON.Frustum = Frustum;
  4225. var Space;
  4226. (function (Space) {
  4227. Space[Space["LOCAL"] = 0] = "LOCAL";
  4228. Space[Space["WORLD"] = 1] = "WORLD";
  4229. Space[Space["BONE"] = 2] = "BONE";
  4230. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4231. var Axis = (function () {
  4232. function Axis() {
  4233. }
  4234. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4235. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4236. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4237. return Axis;
  4238. }());
  4239. BABYLON.Axis = Axis;
  4240. ;
  4241. var BezierCurve = (function () {
  4242. function BezierCurve() {
  4243. }
  4244. /**
  4245. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4246. */
  4247. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4248. // Extract X (which is equal to time here)
  4249. var f0 = 1 - 3 * x2 + 3 * x1;
  4250. var f1 = 3 * x2 - 6 * x1;
  4251. var f2 = 3 * x1;
  4252. var refinedT = t;
  4253. for (var i = 0; i < 5; i++) {
  4254. var refinedT2 = refinedT * refinedT;
  4255. var refinedT3 = refinedT2 * refinedT;
  4256. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4257. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4258. refinedT -= (x - t) * slope;
  4259. refinedT = Math.min(1, Math.max(0, refinedT));
  4260. }
  4261. // Resolve cubic bezier for the given x
  4262. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4263. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4264. Math.pow(refinedT, 3);
  4265. };
  4266. return BezierCurve;
  4267. }());
  4268. BABYLON.BezierCurve = BezierCurve;
  4269. var Orientation;
  4270. (function (Orientation) {
  4271. Orientation[Orientation["CW"] = 0] = "CW";
  4272. Orientation[Orientation["CCW"] = 1] = "CCW";
  4273. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4274. var Angle = (function () {
  4275. /**
  4276. * Creates an Angle object of "radians" radians (float).
  4277. */
  4278. function Angle(radians) {
  4279. var _this = this;
  4280. /**
  4281. * Returns the Angle value in degrees (float).
  4282. */
  4283. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4284. /**
  4285. * Returns the Angle value in radians (float).
  4286. */
  4287. this.radians = function () { return _this._radians; };
  4288. this._radians = radians;
  4289. if (this._radians < 0.0)
  4290. this._radians += (2.0 * Math.PI);
  4291. }
  4292. /**
  4293. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4294. */
  4295. Angle.BetweenTwoPoints = function (a, b) {
  4296. var delta = b.subtract(a);
  4297. var theta = Math.atan2(delta.y, delta.x);
  4298. return new Angle(theta);
  4299. };
  4300. /**
  4301. * Returns a new Angle object from the passed float in radians.
  4302. */
  4303. Angle.FromRadians = function (radians) {
  4304. return new Angle(radians);
  4305. };
  4306. /**
  4307. * Returns a new Angle object from the passed float in degrees.
  4308. */
  4309. Angle.FromDegrees = function (degrees) {
  4310. return new Angle(degrees * Math.PI / 180.0);
  4311. };
  4312. return Angle;
  4313. }());
  4314. BABYLON.Angle = Angle;
  4315. var Arc2 = (function () {
  4316. /**
  4317. * Creates an Arc object from the three passed points : start, middle and end.
  4318. */
  4319. function Arc2(startPoint, midPoint, endPoint) {
  4320. this.startPoint = startPoint;
  4321. this.midPoint = midPoint;
  4322. this.endPoint = endPoint;
  4323. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4324. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4325. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4326. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4327. 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);
  4328. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4329. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4330. var a1 = this.startAngle.degrees();
  4331. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4332. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4333. // angles correction
  4334. if (a2 - a1 > +180.0)
  4335. a2 -= 360.0;
  4336. if (a2 - a1 < -180.0)
  4337. a2 += 360.0;
  4338. if (a3 - a2 > +180.0)
  4339. a3 -= 360.0;
  4340. if (a3 - a2 < -180.0)
  4341. a3 += 360.0;
  4342. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4343. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4344. }
  4345. return Arc2;
  4346. }());
  4347. BABYLON.Arc2 = Arc2;
  4348. var Path2 = (function () {
  4349. /**
  4350. * Creates a Path2 object from the starting 2D coordinates x and y.
  4351. */
  4352. function Path2(x, y) {
  4353. this._points = new Array();
  4354. this._length = 0.0;
  4355. this.closed = false;
  4356. this._points.push(new Vector2(x, y));
  4357. }
  4358. /**
  4359. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4360. * Returns the updated Path2.
  4361. */
  4362. Path2.prototype.addLineTo = function (x, y) {
  4363. if (closed) {
  4364. //Tools.Error("cannot add lines to closed paths");
  4365. return this;
  4366. }
  4367. var newPoint = new Vector2(x, y);
  4368. var previousPoint = this._points[this._points.length - 1];
  4369. this._points.push(newPoint);
  4370. this._length += newPoint.subtract(previousPoint).length();
  4371. return this;
  4372. };
  4373. /**
  4374. * 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.
  4375. * Returns the updated Path2.
  4376. */
  4377. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4378. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4379. if (closed) {
  4380. //Tools.Error("cannot add arcs to closed paths");
  4381. return this;
  4382. }
  4383. var startPoint = this._points[this._points.length - 1];
  4384. var midPoint = new Vector2(midX, midY);
  4385. var endPoint = new Vector2(endX, endY);
  4386. var arc = new Arc2(startPoint, midPoint, endPoint);
  4387. var increment = arc.angle.radians() / numberOfSegments;
  4388. if (arc.orientation === Orientation.CW)
  4389. increment *= -1;
  4390. var currentAngle = arc.startAngle.radians() + increment;
  4391. for (var i = 0; i < numberOfSegments; i++) {
  4392. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4393. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4394. this.addLineTo(x, y);
  4395. currentAngle += increment;
  4396. }
  4397. return this;
  4398. };
  4399. /**
  4400. * Closes the Path2.
  4401. * Returns the Path2.
  4402. */
  4403. Path2.prototype.close = function () {
  4404. this.closed = true;
  4405. return this;
  4406. };
  4407. /**
  4408. * Returns the Path2 total length (float).
  4409. */
  4410. Path2.prototype.length = function () {
  4411. var result = this._length;
  4412. if (!this.closed) {
  4413. var lastPoint = this._points[this._points.length - 1];
  4414. var firstPoint = this._points[0];
  4415. result += (firstPoint.subtract(lastPoint).length());
  4416. }
  4417. return result;
  4418. };
  4419. /**
  4420. * Returns the Path2 internal array of points.
  4421. */
  4422. Path2.prototype.getPoints = function () {
  4423. return this._points;
  4424. };
  4425. /**
  4426. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4427. */
  4428. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4429. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4430. //Tools.Error("normalized length position should be between 0 and 1.");
  4431. return Vector2.Zero();
  4432. }
  4433. var lengthPosition = normalizedLengthPosition * this.length();
  4434. var previousOffset = 0;
  4435. for (var i = 0; i < this._points.length; i++) {
  4436. var j = (i + 1) % this._points.length;
  4437. var a = this._points[i];
  4438. var b = this._points[j];
  4439. var bToA = b.subtract(a);
  4440. var nextOffset = (bToA.length() + previousOffset);
  4441. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4442. var dir = bToA.normalize();
  4443. var localOffset = lengthPosition - previousOffset;
  4444. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4445. }
  4446. previousOffset = nextOffset;
  4447. }
  4448. //Tools.Error("internal error");
  4449. return Vector2.Zero();
  4450. };
  4451. /**
  4452. * Returns a new Path2 starting at the coordinates (x, y).
  4453. */
  4454. Path2.StartingAt = function (x, y) {
  4455. return new Path2(x, y);
  4456. };
  4457. return Path2;
  4458. }());
  4459. BABYLON.Path2 = Path2;
  4460. var Path3D = (function () {
  4461. /**
  4462. * new Path3D(path, normal, raw)
  4463. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4464. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4465. * path : an array of Vector3, the curve axis of the Path3D
  4466. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4467. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4468. */
  4469. function Path3D(path, firstNormal, raw) {
  4470. this.path = path;
  4471. this._curve = new Array();
  4472. this._distances = new Array();
  4473. this._tangents = new Array();
  4474. this._normals = new Array();
  4475. this._binormals = new Array();
  4476. for (var p = 0; p < path.length; p++) {
  4477. this._curve[p] = path[p].clone(); // hard copy
  4478. }
  4479. this._raw = raw || false;
  4480. this._compute(firstNormal);
  4481. }
  4482. /**
  4483. * Returns the Path3D array of successive Vector3 designing its curve.
  4484. */
  4485. Path3D.prototype.getCurve = function () {
  4486. return this._curve;
  4487. };
  4488. /**
  4489. * Returns an array populated with tangent vectors on each Path3D curve point.
  4490. */
  4491. Path3D.prototype.getTangents = function () {
  4492. return this._tangents;
  4493. };
  4494. /**
  4495. * Returns an array populated with normal vectors on each Path3D curve point.
  4496. */
  4497. Path3D.prototype.getNormals = function () {
  4498. return this._normals;
  4499. };
  4500. /**
  4501. * Returns an array populated with binormal vectors on each Path3D curve point.
  4502. */
  4503. Path3D.prototype.getBinormals = function () {
  4504. return this._binormals;
  4505. };
  4506. /**
  4507. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4508. */
  4509. Path3D.prototype.getDistances = function () {
  4510. return this._distances;
  4511. };
  4512. /**
  4513. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4514. * Returns the same object updated.
  4515. */
  4516. Path3D.prototype.update = function (path, firstNormal) {
  4517. for (var p = 0; p < path.length; p++) {
  4518. this._curve[p].x = path[p].x;
  4519. this._curve[p].y = path[p].y;
  4520. this._curve[p].z = path[p].z;
  4521. }
  4522. this._compute(firstNormal);
  4523. return this;
  4524. };
  4525. // private function compute() : computes tangents, normals and binormals
  4526. Path3D.prototype._compute = function (firstNormal) {
  4527. var l = this._curve.length;
  4528. // first and last tangents
  4529. this._tangents[0] = this._getFirstNonNullVector(0);
  4530. if (!this._raw) {
  4531. this._tangents[0].normalize();
  4532. }
  4533. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4534. if (!this._raw) {
  4535. this._tangents[l - 1].normalize();
  4536. }
  4537. // normals and binormals at first point : arbitrary vector with _normalVector()
  4538. var tg0 = this._tangents[0];
  4539. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4540. this._normals[0] = pp0;
  4541. if (!this._raw) {
  4542. this._normals[0].normalize();
  4543. }
  4544. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4545. if (!this._raw) {
  4546. this._binormals[0].normalize();
  4547. }
  4548. this._distances[0] = 0.0;
  4549. // normals and binormals : next points
  4550. var prev; // previous vector (segment)
  4551. var cur; // current vector (segment)
  4552. var curTang; // current tangent
  4553. // previous normal
  4554. var prevBinor; // previous binormal
  4555. for (var i = 1; i < l; i++) {
  4556. // tangents
  4557. prev = this._getLastNonNullVector(i);
  4558. if (i < l - 1) {
  4559. cur = this._getFirstNonNullVector(i);
  4560. this._tangents[i] = prev.add(cur);
  4561. this._tangents[i].normalize();
  4562. }
  4563. this._distances[i] = this._distances[i - 1] + prev.length();
  4564. // normals and binormals
  4565. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4566. curTang = this._tangents[i];
  4567. prevBinor = this._binormals[i - 1];
  4568. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4569. if (!this._raw) {
  4570. this._normals[i].normalize();
  4571. }
  4572. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4573. if (!this._raw) {
  4574. this._binormals[i].normalize();
  4575. }
  4576. }
  4577. };
  4578. // private function getFirstNonNullVector(index)
  4579. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4580. Path3D.prototype._getFirstNonNullVector = function (index) {
  4581. var i = 1;
  4582. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4583. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4584. i++;
  4585. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4586. }
  4587. return nNVector;
  4588. };
  4589. // private function getLastNonNullVector(index)
  4590. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4591. Path3D.prototype._getLastNonNullVector = function (index) {
  4592. var i = 1;
  4593. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4594. while (nLVector.length() === 0 && index > i + 1) {
  4595. i++;
  4596. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4597. }
  4598. return nLVector;
  4599. };
  4600. // private function normalVector(v0, vt, va) :
  4601. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4602. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4603. Path3D.prototype._normalVector = function (v0, vt, va) {
  4604. var normal0;
  4605. var tgl = vt.length();
  4606. if (tgl === 0.0) {
  4607. tgl = 1.0;
  4608. }
  4609. if (va === undefined || va === null) {
  4610. var point;
  4611. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4612. point = new Vector3(0.0, -1.0, 0.0);
  4613. }
  4614. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4615. point = new Vector3(1.0, 0.0, 0.0);
  4616. }
  4617. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4618. point = new Vector3(0.0, 0.0, 1.0);
  4619. }
  4620. normal0 = Vector3.Cross(vt, point);
  4621. }
  4622. else {
  4623. normal0 = Vector3.Cross(vt, va);
  4624. Vector3.CrossToRef(normal0, vt, normal0);
  4625. }
  4626. normal0.normalize();
  4627. return normal0;
  4628. };
  4629. return Path3D;
  4630. }());
  4631. BABYLON.Path3D = Path3D;
  4632. var Curve3 = (function () {
  4633. /**
  4634. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4635. * A Curve3 is designed from a series of successive Vector3.
  4636. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4637. */
  4638. function Curve3(points) {
  4639. this._length = 0.0;
  4640. this._points = points;
  4641. this._length = this._computeLength(points);
  4642. }
  4643. /**
  4644. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4645. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4646. * @param v1 (Vector3) the control point
  4647. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4648. * @param nbPoints (integer) the wanted number of points in the curve
  4649. */
  4650. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4651. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4652. var bez = new Array();
  4653. var equation = function (t, val0, val1, val2) {
  4654. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4655. return res;
  4656. };
  4657. for (var i = 0; i <= nbPoints; i++) {
  4658. 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)));
  4659. }
  4660. return new Curve3(bez);
  4661. };
  4662. /**
  4663. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4664. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4665. * @param v1 (Vector3) the first control point
  4666. * @param v2 (Vector3) the second control point
  4667. * @param v3 (Vector3) the end point of the Cubic Bezier
  4668. * @param nbPoints (integer) the wanted number of points in the curve
  4669. */
  4670. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4671. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4672. var bez = new Array();
  4673. var equation = function (t, val0, val1, val2, val3) {
  4674. 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;
  4675. return res;
  4676. };
  4677. for (var i = 0; i <= nbPoints; i++) {
  4678. 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)));
  4679. }
  4680. return new Curve3(bez);
  4681. };
  4682. /**
  4683. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4684. * @param p1 (Vector3) the origin point of the Hermite Spline
  4685. * @param t1 (Vector3) the tangent vector at the origin point
  4686. * @param p2 (Vector3) the end point of the Hermite Spline
  4687. * @param t2 (Vector3) the tangent vector at the end point
  4688. * @param nbPoints (integer) the wanted number of points in the curve
  4689. */
  4690. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4691. var hermite = new Array();
  4692. var step = 1.0 / nbPoints;
  4693. for (var i = 0; i <= nbPoints; i++) {
  4694. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4695. }
  4696. return new Curve3(hermite);
  4697. };
  4698. /**
  4699. * Returns a Curve3 object along a CatmullRom Spline curve :
  4700. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4701. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4702. */
  4703. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4704. var totalPoints = new Array();
  4705. totalPoints.push(points[0].clone());
  4706. Array.prototype.push.apply(totalPoints, points);
  4707. totalPoints.push(points[points.length - 1].clone());
  4708. var catmullRom = new Array();
  4709. var step = 1.0 / nbPoints;
  4710. for (var i = 0; i < totalPoints.length - 3; i++) {
  4711. var amount = 0.0;
  4712. for (var c = 0; c < nbPoints; c++) {
  4713. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4714. amount += step;
  4715. }
  4716. }
  4717. i--;
  4718. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4719. return new Curve3(catmullRom);
  4720. };
  4721. /**
  4722. * Returns the Curve3 stored array of successive Vector3
  4723. */
  4724. Curve3.prototype.getPoints = function () {
  4725. return this._points;
  4726. };
  4727. /**
  4728. * Returns the computed length (float) of the curve.
  4729. */
  4730. Curve3.prototype.length = function () {
  4731. return this._length;
  4732. };
  4733. /**
  4734. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4735. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4736. * curveA and curveB keep unchanged.
  4737. */
  4738. Curve3.prototype.continue = function (curve) {
  4739. var lastPoint = this._points[this._points.length - 1];
  4740. var continuedPoints = this._points.slice();
  4741. var curvePoints = curve.getPoints();
  4742. for (var i = 1; i < curvePoints.length; i++) {
  4743. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4744. }
  4745. var continuedCurve = new Curve3(continuedPoints);
  4746. return continuedCurve;
  4747. };
  4748. Curve3.prototype._computeLength = function (path) {
  4749. var l = 0;
  4750. for (var i = 1; i < path.length; i++) {
  4751. l += (path[i].subtract(path[i - 1])).length();
  4752. }
  4753. return l;
  4754. };
  4755. return Curve3;
  4756. }());
  4757. BABYLON.Curve3 = Curve3;
  4758. // Vertex formats
  4759. var PositionNormalVertex = (function () {
  4760. function PositionNormalVertex(position, normal) {
  4761. if (position === void 0) { position = Vector3.Zero(); }
  4762. if (normal === void 0) { normal = Vector3.Up(); }
  4763. this.position = position;
  4764. this.normal = normal;
  4765. }
  4766. PositionNormalVertex.prototype.clone = function () {
  4767. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4768. };
  4769. return PositionNormalVertex;
  4770. }());
  4771. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4772. var PositionNormalTextureVertex = (function () {
  4773. function PositionNormalTextureVertex(position, normal, uv) {
  4774. if (position === void 0) { position = Vector3.Zero(); }
  4775. if (normal === void 0) { normal = Vector3.Up(); }
  4776. if (uv === void 0) { uv = Vector2.Zero(); }
  4777. this.position = position;
  4778. this.normal = normal;
  4779. this.uv = uv;
  4780. }
  4781. PositionNormalTextureVertex.prototype.clone = function () {
  4782. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4783. };
  4784. return PositionNormalTextureVertex;
  4785. }());
  4786. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4787. // Temporary pre-allocated objects for engine internal use
  4788. // usage in any internal function :
  4789. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4790. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4791. var Tmp = (function () {
  4792. function Tmp() {
  4793. }
  4794. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4795. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4796. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4797. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4798. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4799. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4800. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4801. Matrix.Zero(), Matrix.Zero(),
  4802. Matrix.Zero(), Matrix.Zero(),
  4803. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4804. return Tmp;
  4805. }());
  4806. BABYLON.Tmp = Tmp;
  4807. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4808. var MathTmp = (function () {
  4809. function MathTmp() {
  4810. }
  4811. MathTmp.Vector3 = [Vector3.Zero()];
  4812. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4813. MathTmp.Quaternion = [Quaternion.Zero()];
  4814. return MathTmp;
  4815. }());
  4816. })(BABYLON || (BABYLON = {}));
  4817. //# sourceMappingURL=babylon.math.js.map
  4818. var BABYLON;
  4819. (function (BABYLON) {
  4820. var Scalar = (function () {
  4821. function Scalar() {
  4822. }
  4823. /**
  4824. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4825. */
  4826. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4827. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4828. var num = a - b;
  4829. return -epsilon <= num && num <= epsilon;
  4830. };
  4831. /**
  4832. * Returns a string : the upper case translation of the number i to hexadecimal.
  4833. */
  4834. Scalar.ToHex = function (i) {
  4835. var str = i.toString(16);
  4836. if (i <= 15) {
  4837. return ("0" + str).toUpperCase();
  4838. }
  4839. return str.toUpperCase();
  4840. };
  4841. /**
  4842. * Returns -1 if value is negative and +1 is value is positive.
  4843. * Returns the value itself if it's equal to zero.
  4844. */
  4845. Scalar.Sign = function (value) {
  4846. value = +value; // convert to a number
  4847. if (value === 0 || isNaN(value))
  4848. return value;
  4849. return value > 0 ? 1 : -1;
  4850. };
  4851. /**
  4852. * Returns the value itself if it's between min and max.
  4853. * Returns min if the value is lower than min.
  4854. * Returns max if the value is greater than max.
  4855. */
  4856. Scalar.Clamp = function (value, min, max) {
  4857. if (min === void 0) { min = 0; }
  4858. if (max === void 0) { max = 1; }
  4859. return Math.min(max, Math.max(min, value));
  4860. };
  4861. /**
  4862. * Returns the log2 of value.
  4863. */
  4864. Scalar.Log2 = function (value) {
  4865. return Math.log(value) * Math.LOG2E;
  4866. };
  4867. /**
  4868. * Loops the value, so that it is never larger than length and never smaller than 0.
  4869. *
  4870. * This is similar to the modulo operator but it works with floating point numbers.
  4871. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4872. * With t = 5 and length = 2.5, the result would be 0.0.
  4873. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4874. */
  4875. Scalar.Repeat = function (value, length) {
  4876. return value - Math.floor(value / length) * length;
  4877. };
  4878. /**
  4879. * Normalize the value between 0.0 and 1.0 using min and max values
  4880. */
  4881. Scalar.Normalize = function (value, min, max) {
  4882. return (value - min) / (max - min);
  4883. };
  4884. /**
  4885. * Denormalize the value from 0.0 and 1.0 using min and max values
  4886. */
  4887. Scalar.Denormalize = function (normalized, min, max) {
  4888. return (normalized * (max - min) + min);
  4889. };
  4890. /**
  4891. * Calculates the shortest difference between two given angles given in degrees.
  4892. */
  4893. Scalar.DeltaAngle = function (current, target) {
  4894. var num = Scalar.Repeat(target - current, 360.0);
  4895. if (num > 180.0) {
  4896. num -= 360.0;
  4897. }
  4898. return num;
  4899. };
  4900. /**
  4901. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4902. *
  4903. * The returned value will move back and forth between 0 and length
  4904. */
  4905. Scalar.PingPong = function (tx, length) {
  4906. var t = Scalar.Repeat(tx, length * 2.0);
  4907. return length - Math.abs(t - length);
  4908. };
  4909. /**
  4910. * Interpolates between min and max with smoothing at the limits.
  4911. *
  4912. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4913. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4914. */
  4915. Scalar.SmoothStep = function (from, to, tx) {
  4916. var t = Scalar.Clamp(tx);
  4917. t = -2.0 * t * t * t + 3.0 * t * t;
  4918. return to * t + from * (1.0 - t);
  4919. };
  4920. /**
  4921. * Moves a value current towards target.
  4922. *
  4923. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4924. * Negative values of maxDelta pushes the value away from target.
  4925. */
  4926. Scalar.MoveTowards = function (current, target, maxDelta) {
  4927. var result = 0;
  4928. if (Math.abs(target - current) <= maxDelta) {
  4929. result = target;
  4930. }
  4931. else {
  4932. result = current + Scalar.Sign(target - current) * maxDelta;
  4933. }
  4934. return result;
  4935. };
  4936. /**
  4937. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4938. *
  4939. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4940. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4941. */
  4942. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4943. var num = Scalar.DeltaAngle(current, target);
  4944. var result = 0;
  4945. if (-maxDelta < num && num < maxDelta) {
  4946. result = target;
  4947. }
  4948. else {
  4949. target = current + num;
  4950. result = Scalar.MoveTowards(current, target, maxDelta);
  4951. }
  4952. return result;
  4953. };
  4954. /**
  4955. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4956. */
  4957. Scalar.Lerp = function (start, end, amount) {
  4958. return start + ((end - start) * amount);
  4959. };
  4960. /**
  4961. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4962. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4963. */
  4964. Scalar.LerpAngle = function (start, end, amount) {
  4965. var num = Scalar.Repeat(end - start, 360.0);
  4966. if (num > 180.0) {
  4967. num -= 360.0;
  4968. }
  4969. return start + num * Scalar.Clamp(amount);
  4970. };
  4971. /**
  4972. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4973. */
  4974. Scalar.InverseLerp = function (a, b, value) {
  4975. var result = 0;
  4976. if (a != b) {
  4977. result = Scalar.Clamp((value - a) / (b - a));
  4978. }
  4979. else {
  4980. result = 0.0;
  4981. }
  4982. return result;
  4983. };
  4984. /**
  4985. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  4986. */
  4987. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4988. var squared = amount * amount;
  4989. var cubed = amount * squared;
  4990. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4991. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4992. var part3 = (cubed - (2.0 * squared)) + amount;
  4993. var part4 = cubed - squared;
  4994. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  4995. };
  4996. /**
  4997. * Returns a random float number between and min and max values
  4998. */
  4999. Scalar.RandomRange = function (min, max) {
  5000. if (min === max)
  5001. return min;
  5002. return ((Math.random() * (max - min)) + min);
  5003. };
  5004. /**
  5005. * This function returns percentage of a number in a given range.
  5006. *
  5007. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5008. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5009. */
  5010. Scalar.RangeToPercent = function (number, min, max) {
  5011. return ((number - min) / (max - min));
  5012. };
  5013. /**
  5014. * This function returns number that corresponds to the percentage in a given range.
  5015. *
  5016. * PercentToRange(0.34,0,100) will return 34.
  5017. */
  5018. Scalar.PercentToRange = function (percent, min, max) {
  5019. return ((max - min) * percent + min);
  5020. };
  5021. return Scalar;
  5022. }());
  5023. BABYLON.Scalar = Scalar;
  5024. })(BABYLON || (BABYLON = {}));
  5025. //# sourceMappingURL=babylon.math.scalar.js.map
  5026. //# sourceMappingURL=babylon.mixins.js.map
  5027. var BABYLON;
  5028. (function (BABYLON) {
  5029. var __decoratorInitialStore = {};
  5030. var __mergedStore = {};
  5031. var _copySource = function (creationFunction, source, instanciate) {
  5032. var destination = creationFunction();
  5033. // Tags
  5034. if (BABYLON.Tags) {
  5035. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5036. }
  5037. var classStore = getMergedStore(destination);
  5038. // Properties
  5039. for (var property in classStore) {
  5040. var propertyDescriptor = classStore[property];
  5041. var sourceProperty = source[property];
  5042. var propertyType = propertyDescriptor.type;
  5043. if (sourceProperty !== undefined && sourceProperty !== null) {
  5044. switch (propertyType) {
  5045. case 0: // Value
  5046. case 6:// Mesh reference
  5047. destination[property] = sourceProperty;
  5048. break;
  5049. case 1: // Texture
  5050. case 2: // Color3
  5051. case 3: // FresnelParameters
  5052. case 4: // Vector2
  5053. case 5: // Vector3
  5054. case 7:// Color Curves
  5055. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5056. break;
  5057. }
  5058. }
  5059. }
  5060. return destination;
  5061. };
  5062. function getDirectStore(target) {
  5063. var classKey = target.getClassName();
  5064. if (!__decoratorInitialStore[classKey]) {
  5065. __decoratorInitialStore[classKey] = {};
  5066. }
  5067. return __decoratorInitialStore[classKey];
  5068. }
  5069. /**
  5070. * Return the list of properties flagged as serializable
  5071. * @param target: host object
  5072. */
  5073. function getMergedStore(target) {
  5074. var classKey = target.getClassName();
  5075. if (__mergedStore[classKey]) {
  5076. return __mergedStore[classKey];
  5077. }
  5078. __mergedStore[classKey] = {};
  5079. var store = __mergedStore[classKey];
  5080. var currentTarget = target;
  5081. var currentKey = classKey;
  5082. while (currentKey) {
  5083. var initialStore = __decoratorInitialStore[currentKey];
  5084. for (var property in initialStore) {
  5085. store[property] = initialStore[property];
  5086. }
  5087. var parent_1 = void 0;
  5088. var done = false;
  5089. do {
  5090. parent_1 = Object.getPrototypeOf(currentTarget);
  5091. if (!parent_1.getClassName) {
  5092. done = true;
  5093. break;
  5094. }
  5095. if (parent_1.getClassName() !== currentKey) {
  5096. break;
  5097. }
  5098. currentTarget = parent_1;
  5099. } while (parent_1);
  5100. if (done) {
  5101. break;
  5102. }
  5103. currentKey = parent_1.getClassName();
  5104. currentTarget = parent_1;
  5105. }
  5106. return store;
  5107. }
  5108. function generateSerializableMember(type, sourceName) {
  5109. return function (target, propertyKey) {
  5110. var classStore = getDirectStore(target);
  5111. if (!classStore[propertyKey]) {
  5112. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5113. }
  5114. };
  5115. }
  5116. function generateExpandMember(setCallback, targetKey) {
  5117. return function (target, propertyKey) {
  5118. var key = targetKey || ("_" + propertyKey);
  5119. Object.defineProperty(target, propertyKey, {
  5120. get: function () {
  5121. return this[key];
  5122. },
  5123. set: function (value) {
  5124. if (this[key] === value) {
  5125. return;
  5126. }
  5127. this[key] = value;
  5128. target[setCallback].apply(this);
  5129. },
  5130. enumerable: true,
  5131. configurable: true
  5132. });
  5133. };
  5134. }
  5135. function expandToProperty(callback, targetKey) {
  5136. return generateExpandMember(callback, targetKey);
  5137. }
  5138. BABYLON.expandToProperty = expandToProperty;
  5139. function serialize(sourceName) {
  5140. return generateSerializableMember(0, sourceName); // value member
  5141. }
  5142. BABYLON.serialize = serialize;
  5143. function serializeAsTexture(sourceName) {
  5144. return generateSerializableMember(1, sourceName); // texture member
  5145. }
  5146. BABYLON.serializeAsTexture = serializeAsTexture;
  5147. function serializeAsColor3(sourceName) {
  5148. return generateSerializableMember(2, sourceName); // color3 member
  5149. }
  5150. BABYLON.serializeAsColor3 = serializeAsColor3;
  5151. function serializeAsFresnelParameters(sourceName) {
  5152. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5153. }
  5154. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5155. function serializeAsVector2(sourceName) {
  5156. return generateSerializableMember(4, sourceName); // vector2 member
  5157. }
  5158. BABYLON.serializeAsVector2 = serializeAsVector2;
  5159. function serializeAsVector3(sourceName) {
  5160. return generateSerializableMember(5, sourceName); // vector3 member
  5161. }
  5162. BABYLON.serializeAsVector3 = serializeAsVector3;
  5163. function serializeAsMeshReference(sourceName) {
  5164. return generateSerializableMember(6, sourceName); // mesh reference member
  5165. }
  5166. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5167. function serializeAsColorCurves(sourceName) {
  5168. return generateSerializableMember(7, sourceName); // color curves
  5169. }
  5170. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5171. function serializeAsColor4(sourceName) {
  5172. return generateSerializableMember(8, sourceName); // color 4
  5173. }
  5174. BABYLON.serializeAsColor4 = serializeAsColor4;
  5175. function serializeAsImageProcessingConfiguration(sourceName) {
  5176. return generateSerializableMember(9, sourceName); // image processing
  5177. }
  5178. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5179. var SerializationHelper = (function () {
  5180. function SerializationHelper() {
  5181. }
  5182. SerializationHelper.Serialize = function (entity, serializationObject) {
  5183. if (!serializationObject) {
  5184. serializationObject = {};
  5185. }
  5186. // Tags
  5187. if (BABYLON.Tags) {
  5188. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5189. }
  5190. var serializedProperties = getMergedStore(entity);
  5191. // Properties
  5192. for (var property in serializedProperties) {
  5193. var propertyDescriptor = serializedProperties[property];
  5194. var targetPropertyName = propertyDescriptor.sourceName || property;
  5195. var propertyType = propertyDescriptor.type;
  5196. var sourceProperty = entity[property];
  5197. if (sourceProperty !== undefined && sourceProperty !== null) {
  5198. switch (propertyType) {
  5199. case 0:// Value
  5200. serializationObject[targetPropertyName] = sourceProperty;
  5201. break;
  5202. case 1:// Texture
  5203. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5204. break;
  5205. case 2:// Color3
  5206. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5207. break;
  5208. case 3:// FresnelParameters
  5209. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5210. break;
  5211. case 4:// Vector2
  5212. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5213. break;
  5214. case 5:// Vector3
  5215. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5216. break;
  5217. case 6:// Mesh reference
  5218. serializationObject[targetPropertyName] = sourceProperty.id;
  5219. break;
  5220. case 7:// Color Curves
  5221. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5222. break;
  5223. case 8:// Color 4
  5224. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5225. break;
  5226. case 9:// Image Processing
  5227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5228. break;
  5229. }
  5230. }
  5231. }
  5232. return serializationObject;
  5233. };
  5234. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5235. var destination = creationFunction();
  5236. // Tags
  5237. if (BABYLON.Tags) {
  5238. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5239. }
  5240. var classStore = getMergedStore(destination);
  5241. // Properties
  5242. for (var property in classStore) {
  5243. var propertyDescriptor = classStore[property];
  5244. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5245. var propertyType = propertyDescriptor.type;
  5246. if (sourceProperty !== undefined && sourceProperty !== null) {
  5247. switch (propertyType) {
  5248. case 0:// Value
  5249. destination[property] = sourceProperty;
  5250. break;
  5251. case 1:// Texture
  5252. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5253. break;
  5254. case 2:// Color3
  5255. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5256. break;
  5257. case 3:// FresnelParameters
  5258. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5259. break;
  5260. case 4:// Vector2
  5261. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5262. break;
  5263. case 5:// Vector3
  5264. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5265. break;
  5266. case 6:// Mesh reference
  5267. destination[property] = scene.getLastMeshByID(sourceProperty);
  5268. break;
  5269. case 7:// Color Curves
  5270. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5271. break;
  5272. case 8:// Color 4
  5273. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5274. break;
  5275. case 9:// Image Processing
  5276. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5277. break;
  5278. }
  5279. }
  5280. }
  5281. return destination;
  5282. };
  5283. SerializationHelper.Clone = function (creationFunction, source) {
  5284. return _copySource(creationFunction, source, false);
  5285. };
  5286. SerializationHelper.Instanciate = function (creationFunction, source) {
  5287. return _copySource(creationFunction, source, true);
  5288. };
  5289. return SerializationHelper;
  5290. }());
  5291. BABYLON.SerializationHelper = SerializationHelper;
  5292. })(BABYLON || (BABYLON = {}));
  5293. //# sourceMappingURL=babylon.decorators.js.map
  5294. var BABYLON;
  5295. (function (BABYLON) {
  5296. /**
  5297. * A class serves as a medium between the observable and its observers
  5298. */
  5299. var EventState = (function () {
  5300. /**
  5301. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5302. */
  5303. function EventState(mask, skipNextObservers) {
  5304. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5305. this.initalize(mask, skipNextObservers);
  5306. }
  5307. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5308. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5309. this.mask = mask;
  5310. this.skipNextObservers = skipNextObservers;
  5311. return this;
  5312. };
  5313. return EventState;
  5314. }());
  5315. BABYLON.EventState = EventState;
  5316. /**
  5317. * Represent an Observer registered to a given Observable object.
  5318. */
  5319. var Observer = (function () {
  5320. function Observer(callback, mask) {
  5321. this.callback = callback;
  5322. this.mask = mask;
  5323. }
  5324. return Observer;
  5325. }());
  5326. BABYLON.Observer = Observer;
  5327. /**
  5328. * The Observable class is a simple implementation of the Observable pattern.
  5329. * 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.
  5330. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5331. * 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).
  5332. * 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.
  5333. */
  5334. var Observable = (function () {
  5335. function Observable() {
  5336. this._observers = new Array();
  5337. this._eventState = new EventState(0);
  5338. }
  5339. /**
  5340. * Create a new Observer with the specified callback
  5341. * @param callback the callback that will be executed for that Observer
  5342. * @param mask the mask used to filter observers
  5343. * @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.
  5344. */
  5345. Observable.prototype.add = function (callback, mask, insertFirst) {
  5346. if (mask === void 0) { mask = -1; }
  5347. if (insertFirst === void 0) { insertFirst = false; }
  5348. if (!callback) {
  5349. return null;
  5350. }
  5351. var observer = new Observer(callback, mask);
  5352. if (insertFirst) {
  5353. this._observers.unshift(observer);
  5354. }
  5355. else {
  5356. this._observers.push(observer);
  5357. }
  5358. return observer;
  5359. };
  5360. /**
  5361. * Remove an Observer from the Observable object
  5362. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5363. */
  5364. Observable.prototype.remove = function (observer) {
  5365. var index = this._observers.indexOf(observer);
  5366. if (index !== -1) {
  5367. this._observers.splice(index, 1);
  5368. return true;
  5369. }
  5370. return false;
  5371. };
  5372. /**
  5373. * Remove a callback from the Observable object
  5374. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5375. */
  5376. Observable.prototype.removeCallback = function (callback) {
  5377. for (var index = 0; index < this._observers.length; index++) {
  5378. if (this._observers[index].callback === callback) {
  5379. this._observers.splice(index, 1);
  5380. return true;
  5381. }
  5382. }
  5383. return false;
  5384. };
  5385. /**
  5386. * Notify all Observers by calling their respective callback with the given data
  5387. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5388. * @param eventData
  5389. * @param mask
  5390. */
  5391. Observable.prototype.notifyObservers = function (eventData, mask) {
  5392. if (mask === void 0) { mask = -1; }
  5393. var state = this._eventState;
  5394. state.mask = mask;
  5395. state.skipNextObservers = false;
  5396. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5397. var obs = _a[_i];
  5398. if (obs.mask & mask) {
  5399. obs.callback(eventData, state);
  5400. }
  5401. if (state.skipNextObservers) {
  5402. return false;
  5403. }
  5404. }
  5405. return true;
  5406. };
  5407. /**
  5408. * return true is the Observable has at least one Observer registered
  5409. */
  5410. Observable.prototype.hasObservers = function () {
  5411. return this._observers.length > 0;
  5412. };
  5413. /**
  5414. * Clear the list of observers
  5415. */
  5416. Observable.prototype.clear = function () {
  5417. this._observers = new Array();
  5418. };
  5419. /**
  5420. * Clone the current observable
  5421. */
  5422. Observable.prototype.clone = function () {
  5423. var result = new Observable();
  5424. result._observers = this._observers.slice(0);
  5425. return result;
  5426. };
  5427. /**
  5428. * Does this observable handles observer registered with a given mask
  5429. * @param {number} trigger - the mask to be tested
  5430. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5431. **/
  5432. Observable.prototype.hasSpecificMask = function (mask) {
  5433. if (mask === void 0) { mask = -1; }
  5434. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5435. var obs = _a[_i];
  5436. if (obs.mask & mask || obs.mask === mask) {
  5437. return true;
  5438. }
  5439. }
  5440. return false;
  5441. };
  5442. return Observable;
  5443. }());
  5444. BABYLON.Observable = Observable;
  5445. })(BABYLON || (BABYLON = {}));
  5446. //# sourceMappingURL=babylon.observable.js.map
  5447. var BABYLON;
  5448. (function (BABYLON) {
  5449. var SmartArray = (function () {
  5450. function SmartArray(capacity) {
  5451. this.length = 0;
  5452. this._duplicateId = 0;
  5453. this.data = new Array(capacity);
  5454. this._id = SmartArray._GlobalId++;
  5455. }
  5456. SmartArray.prototype.push = function (value) {
  5457. this.data[this.length++] = value;
  5458. if (this.length > this.data.length) {
  5459. this.data.length *= 2;
  5460. }
  5461. if (!value.__smartArrayFlags) {
  5462. value.__smartArrayFlags = {};
  5463. }
  5464. value.__smartArrayFlags[this._id] = this._duplicateId;
  5465. };
  5466. SmartArray.prototype.forEach = function (func) {
  5467. for (var index = 0; index < this.length; index++) {
  5468. func(this.data[index]);
  5469. }
  5470. };
  5471. SmartArray.prototype.pushNoDuplicate = function (value) {
  5472. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5473. return false;
  5474. }
  5475. this.push(value);
  5476. return true;
  5477. };
  5478. SmartArray.prototype.sort = function (compareFn) {
  5479. this.data.sort(compareFn);
  5480. };
  5481. SmartArray.prototype.reset = function () {
  5482. this.length = 0;
  5483. this._duplicateId++;
  5484. };
  5485. SmartArray.prototype.dispose = function () {
  5486. this.reset();
  5487. if (this.data) {
  5488. this.data.length = 0;
  5489. this.data = null;
  5490. }
  5491. };
  5492. SmartArray.prototype.concat = function (array) {
  5493. if (array.length === 0) {
  5494. return;
  5495. }
  5496. if (this.length + array.length > this.data.length) {
  5497. this.data.length = (this.length + array.length) * 2;
  5498. }
  5499. for (var index = 0; index < array.length; index++) {
  5500. this.data[this.length++] = (array.data || array)[index];
  5501. }
  5502. };
  5503. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5504. if (array.length === 0) {
  5505. return;
  5506. }
  5507. if (this.length + array.length > this.data.length) {
  5508. this.data.length = (this.length + array.length) * 2;
  5509. }
  5510. for (var index = 0; index < array.length; index++) {
  5511. var item = (array.data || array)[index];
  5512. this.pushNoDuplicate(item);
  5513. }
  5514. };
  5515. SmartArray.prototype.indexOf = function (value) {
  5516. var position = this.data.indexOf(value);
  5517. if (position >= this.length) {
  5518. return -1;
  5519. }
  5520. return position;
  5521. };
  5522. SmartArray.prototype.contains = function (value) {
  5523. return this.data.indexOf(value) !== -1;
  5524. };
  5525. // Statics
  5526. SmartArray._GlobalId = 0;
  5527. return SmartArray;
  5528. }());
  5529. BABYLON.SmartArray = SmartArray;
  5530. })(BABYLON || (BABYLON = {}));
  5531. //# sourceMappingURL=babylon.smartArray.js.map
  5532. var BABYLON;
  5533. (function (BABYLON) {
  5534. // Screenshots
  5535. var screenshotCanvas;
  5536. var cloneValue = function (source, destinationObject) {
  5537. if (!source)
  5538. return null;
  5539. if (source instanceof BABYLON.Mesh) {
  5540. return null;
  5541. }
  5542. if (source instanceof BABYLON.SubMesh) {
  5543. return source.clone(destinationObject);
  5544. }
  5545. else if (source.clone) {
  5546. return source.clone();
  5547. }
  5548. return null;
  5549. };
  5550. var Tools = (function () {
  5551. function Tools() {
  5552. }
  5553. ;
  5554. /**
  5555. * Interpolates between a and b via alpha
  5556. * @param a The lower value (returned when alpha = 0)
  5557. * @param b The upper value (returned when alpha = 1)
  5558. * @param alpha The interpolation-factor
  5559. * @return The mixed value
  5560. */
  5561. Tools.Mix = function (a, b, alpha) {
  5562. return a * (1 - alpha) + b * alpha;
  5563. };
  5564. Tools.Instantiate = function (className) {
  5565. var arr = className.split(".");
  5566. var fn = (window || this);
  5567. for (var i = 0, len = arr.length; i < len; i++) {
  5568. fn = fn[arr[i]];
  5569. }
  5570. if (typeof fn !== "function") {
  5571. return null;
  5572. }
  5573. return fn;
  5574. };
  5575. Tools.SetImmediate = function (action) {
  5576. if (window.setImmediate) {
  5577. window.setImmediate(action);
  5578. }
  5579. else {
  5580. setTimeout(action, 1);
  5581. }
  5582. };
  5583. Tools.IsExponentOfTwo = function (value) {
  5584. var count = 1;
  5585. do {
  5586. count *= 2;
  5587. } while (count < value);
  5588. return count === value;
  5589. };
  5590. /**
  5591. * Find the next highest power of two.
  5592. * @param x Number to start search from.
  5593. * @return Next highest power of two.
  5594. */
  5595. Tools.CeilingPOT = function (x) {
  5596. x--;
  5597. x |= x >> 1;
  5598. x |= x >> 2;
  5599. x |= x >> 4;
  5600. x |= x >> 8;
  5601. x |= x >> 16;
  5602. x++;
  5603. return x;
  5604. };
  5605. /**
  5606. * Find the next lowest power of two.
  5607. * @param x Number to start search from.
  5608. * @return Next lowest power of two.
  5609. */
  5610. Tools.FloorPOT = function (x) {
  5611. x = x | (x >> 1);
  5612. x = x | (x >> 2);
  5613. x = x | (x >> 4);
  5614. x = x | (x >> 8);
  5615. x = x | (x >> 16);
  5616. return x - (x >> 1);
  5617. };
  5618. /**
  5619. * Find the nearest power of two.
  5620. * @param x Number to start search from.
  5621. * @return Next nearest power of two.
  5622. */
  5623. Tools.NearestPOT = function (x) {
  5624. var c = Tools.CeilingPOT(x);
  5625. var f = Tools.FloorPOT(x);
  5626. return (c - x) > (x - f) ? f : c;
  5627. };
  5628. Tools.GetExponentOfTwo = function (value, max, mode) {
  5629. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5630. var pot;
  5631. switch (mode) {
  5632. case BABYLON.Engine.SCALEMODE_FLOOR:
  5633. pot = Tools.FloorPOT(value);
  5634. break;
  5635. case BABYLON.Engine.SCALEMODE_NEAREST:
  5636. pot = Tools.NearestPOT(value);
  5637. break;
  5638. case BABYLON.Engine.SCALEMODE_CEILING:
  5639. pot = Tools.CeilingPOT(value);
  5640. break;
  5641. }
  5642. return Math.min(pot, max);
  5643. };
  5644. Tools.GetFilename = function (path) {
  5645. var index = path.lastIndexOf("/");
  5646. if (index < 0)
  5647. return path;
  5648. return path.substring(index + 1);
  5649. };
  5650. Tools.GetDOMTextContent = function (element) {
  5651. var result = "";
  5652. var child = element.firstChild;
  5653. while (child) {
  5654. if (child.nodeType === 3) {
  5655. result += child.textContent;
  5656. }
  5657. child = child.nextSibling;
  5658. }
  5659. return result;
  5660. };
  5661. Tools.ToDegrees = function (angle) {
  5662. return angle * 180 / Math.PI;
  5663. };
  5664. Tools.ToRadians = function (angle) {
  5665. return angle * Math.PI / 180;
  5666. };
  5667. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5668. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5669. var output = "";
  5670. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5671. var i = 0;
  5672. var bytes = new Uint8Array(buffer);
  5673. while (i < bytes.length) {
  5674. chr1 = bytes[i++];
  5675. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5676. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5677. enc1 = chr1 >> 2;
  5678. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5679. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5680. enc4 = chr3 & 63;
  5681. if (isNaN(chr2)) {
  5682. enc3 = enc4 = 64;
  5683. }
  5684. else if (isNaN(chr3)) {
  5685. enc4 = 64;
  5686. }
  5687. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5688. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5689. }
  5690. return "data:image/png;base64," + output;
  5691. };
  5692. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5693. if (bias === void 0) { bias = null; }
  5694. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5695. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5696. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5697. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5698. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5699. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5700. }
  5701. if (bias) {
  5702. minimum.x -= minimum.x * bias.x + bias.y;
  5703. minimum.y -= minimum.y * bias.x + bias.y;
  5704. minimum.z -= minimum.z * bias.x + bias.y;
  5705. maximum.x += maximum.x * bias.x + bias.y;
  5706. maximum.y += maximum.y * bias.x + bias.y;
  5707. maximum.z += maximum.z * bias.x + bias.y;
  5708. }
  5709. return {
  5710. minimum: minimum,
  5711. maximum: maximum
  5712. };
  5713. };
  5714. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5715. if (bias === void 0) { bias = null; }
  5716. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5717. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5718. if (!stride) {
  5719. stride = 3;
  5720. }
  5721. for (var index = start; index < start + count; index++) {
  5722. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5723. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5724. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5725. }
  5726. if (bias) {
  5727. minimum.x -= minimum.x * bias.x + bias.y;
  5728. minimum.y -= minimum.y * bias.x + bias.y;
  5729. minimum.z -= minimum.z * bias.x + bias.y;
  5730. maximum.x += maximum.x * bias.x + bias.y;
  5731. maximum.y += maximum.y * bias.x + bias.y;
  5732. maximum.z += maximum.z * bias.x + bias.y;
  5733. }
  5734. return {
  5735. minimum: minimum,
  5736. maximum: maximum
  5737. };
  5738. };
  5739. Tools.Vector2ArrayFeeder = function (array) {
  5740. return function (index) {
  5741. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5742. var length = isFloatArray ? array.length / 2 : array.length;
  5743. if (index >= length) {
  5744. return null;
  5745. }
  5746. if (isFloatArray) {
  5747. var fa = array;
  5748. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5749. }
  5750. var a = array;
  5751. return a[index];
  5752. };
  5753. };
  5754. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5755. if (bias === void 0) { bias = null; }
  5756. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5757. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5758. var i = 0;
  5759. var cur = feeder(i++);
  5760. while (cur) {
  5761. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5762. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5763. cur = feeder(i++);
  5764. }
  5765. if (bias) {
  5766. minimum.x -= minimum.x * bias.x + bias.y;
  5767. minimum.y -= minimum.y * bias.x + bias.y;
  5768. maximum.x += maximum.x * bias.x + bias.y;
  5769. maximum.y += maximum.y * bias.x + bias.y;
  5770. }
  5771. return {
  5772. minimum: minimum,
  5773. maximum: maximum
  5774. };
  5775. };
  5776. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5777. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5778. return undefined;
  5779. return Array.isArray(obj) ? obj : [obj];
  5780. };
  5781. // Misc.
  5782. Tools.GetPointerPrefix = function () {
  5783. var eventPrefix = "pointer";
  5784. // Check if pointer events are supported
  5785. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5786. eventPrefix = "mouse";
  5787. }
  5788. return eventPrefix;
  5789. };
  5790. /**
  5791. * @param func - the function to be called
  5792. * @param requester - the object that will request the next frame. Falls back to window.
  5793. */
  5794. Tools.QueueNewFrame = function (func, requester) {
  5795. if (requester === void 0) { requester = window; }
  5796. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5797. /*if(requester.isPresenting) {
  5798. return;
  5799. } else*/ if (requester.requestAnimationFrame)
  5800. requester.requestAnimationFrame(func);
  5801. else if (requester.msRequestAnimationFrame)
  5802. requester.msRequestAnimationFrame(func);
  5803. else if (requester.webkitRequestAnimationFrame)
  5804. requester.webkitRequestAnimationFrame(func);
  5805. else if (requester.mozRequestAnimationFrame)
  5806. requester.mozRequestAnimationFrame(func);
  5807. else if (requester.oRequestAnimationFrame)
  5808. requester.oRequestAnimationFrame(func);
  5809. else {
  5810. window.setTimeout(func, 16);
  5811. }
  5812. };
  5813. Tools.RequestFullscreen = function (element) {
  5814. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5815. if (!requestFunction)
  5816. return;
  5817. requestFunction.call(element);
  5818. };
  5819. Tools.ExitFullscreen = function () {
  5820. if (document.exitFullscreen) {
  5821. document.exitFullscreen();
  5822. }
  5823. else if (document.mozCancelFullScreen) {
  5824. document.mozCancelFullScreen();
  5825. }
  5826. else if (document.webkitCancelFullScreen) {
  5827. document.webkitCancelFullScreen();
  5828. }
  5829. else if (document.msCancelFullScreen) {
  5830. document.msCancelFullScreen();
  5831. }
  5832. };
  5833. Tools.SetCorsBehavior = function (url, img) {
  5834. if (Tools.CorsBehavior) {
  5835. switch (typeof (Tools.CorsBehavior)) {
  5836. case "function":
  5837. var result = Tools.CorsBehavior(url);
  5838. if (result) {
  5839. img.crossOrigin = result;
  5840. }
  5841. break;
  5842. case "string":
  5843. default:
  5844. img.crossOrigin = Tools.CorsBehavior;
  5845. break;
  5846. }
  5847. }
  5848. };
  5849. // External files
  5850. Tools.CleanUrl = function (url) {
  5851. url = url.replace(/#/mg, "%23");
  5852. return url;
  5853. };
  5854. Tools.LoadImage = function (url, onload, onerror, database) {
  5855. if (url instanceof ArrayBuffer) {
  5856. url = Tools.EncodeArrayBufferTobase64(url);
  5857. }
  5858. url = Tools.CleanUrl(url);
  5859. url = Tools.PreprocessUrl(url);
  5860. var img = new Image();
  5861. if (url.substr(0, 5) !== "data:") {
  5862. Tools.SetCorsBehavior(url, img);
  5863. }
  5864. img.onload = function () {
  5865. onload(img);
  5866. };
  5867. img.onerror = function (err) {
  5868. Tools.Error("Error while trying to load image: " + url);
  5869. if (Tools.UseFallbackTexture) {
  5870. img.src = Tools.fallbackTexture;
  5871. onload(img);
  5872. }
  5873. else {
  5874. onerror();
  5875. }
  5876. };
  5877. var noIndexedDB = function () {
  5878. img.src = url;
  5879. };
  5880. var loadFromIndexedDB = function () {
  5881. database.loadImageFromDB(url, img);
  5882. };
  5883. //ANY database to do!
  5884. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5885. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5886. }
  5887. else {
  5888. if (url.indexOf("file:") !== 0) {
  5889. noIndexedDB();
  5890. }
  5891. else {
  5892. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5893. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5894. try {
  5895. var blobURL;
  5896. try {
  5897. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5898. }
  5899. catch (ex) {
  5900. // Chrome doesn't support oneTimeOnly parameter
  5901. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5902. }
  5903. img.src = blobURL;
  5904. }
  5905. catch (e) {
  5906. img.src = null;
  5907. }
  5908. }
  5909. else {
  5910. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5911. img.src = Tools.fallbackTexture;
  5912. }
  5913. }
  5914. }
  5915. return img;
  5916. };
  5917. //ANY
  5918. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5919. url = Tools.CleanUrl(url);
  5920. url = Tools.PreprocessUrl(url);
  5921. var noIndexedDB = function () {
  5922. var request = new XMLHttpRequest();
  5923. var loadUrl = Tools.BaseUrl + url;
  5924. request.open('GET', loadUrl, true);
  5925. if (useArrayBuffer) {
  5926. request.responseType = "arraybuffer";
  5927. }
  5928. request.onprogress = progressCallBack;
  5929. request.onreadystatechange = function () {
  5930. // In case of undefined state in some browsers.
  5931. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5932. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5933. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5934. callback(!useArrayBuffer ? request.responseText : request.response);
  5935. }
  5936. else {
  5937. if (onError) {
  5938. onError(request);
  5939. }
  5940. else {
  5941. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5942. }
  5943. }
  5944. }
  5945. };
  5946. request.send(null);
  5947. };
  5948. var loadFromIndexedDB = function () {
  5949. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5950. };
  5951. if (url.indexOf("file:") !== -1) {
  5952. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5953. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5954. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5955. }
  5956. else {
  5957. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5958. }
  5959. }
  5960. else {
  5961. // Caching all files
  5962. if (database && database.enableSceneOffline) {
  5963. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5964. }
  5965. else {
  5966. noIndexedDB();
  5967. }
  5968. }
  5969. };
  5970. /**
  5971. * Load a script (identified by an url). When the url returns, the
  5972. * content of this file is added into a new script element, attached to the DOM (body element)
  5973. */
  5974. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5975. var head = document.getElementsByTagName('head')[0];
  5976. var script = document.createElement('script');
  5977. script.type = 'text/javascript';
  5978. script.src = scriptUrl;
  5979. var self = this;
  5980. script.onload = function () {
  5981. if (onSuccess) {
  5982. onSuccess();
  5983. }
  5984. };
  5985. script.onerror = function () {
  5986. if (onError) {
  5987. onError();
  5988. }
  5989. };
  5990. head.appendChild(script);
  5991. };
  5992. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5993. var reader = new FileReader();
  5994. reader.onload = function (e) {
  5995. //target doesn't have result from ts 1.3
  5996. callback(e.target['result']);
  5997. };
  5998. reader.onprogress = progressCallback;
  5999. reader.readAsDataURL(fileToLoad);
  6000. };
  6001. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6002. var reader = new FileReader();
  6003. reader.onerror = function (e) {
  6004. Tools.Log("Error while reading file: " + fileToLoad.name);
  6005. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6006. };
  6007. reader.onload = function (e) {
  6008. //target doesn't have result from ts 1.3
  6009. callback(e.target['result']);
  6010. };
  6011. reader.onprogress = progressCallBack;
  6012. if (!useArrayBuffer) {
  6013. // Asynchronous read
  6014. reader.readAsText(fileToLoad);
  6015. }
  6016. else {
  6017. reader.readAsArrayBuffer(fileToLoad);
  6018. }
  6019. };
  6020. //returns a downloadable url to a file content.
  6021. Tools.FileAsURL = function (content) {
  6022. var fileBlob = new Blob([content]);
  6023. var url = window.URL || window.webkitURL;
  6024. var link = url.createObjectURL(fileBlob);
  6025. return link;
  6026. };
  6027. // Misc.
  6028. Tools.Format = function (value, decimals) {
  6029. if (decimals === void 0) { decimals = 2; }
  6030. return value.toFixed(decimals);
  6031. };
  6032. Tools.CheckExtends = function (v, min, max) {
  6033. if (v.x < min.x)
  6034. min.x = v.x;
  6035. if (v.y < min.y)
  6036. min.y = v.y;
  6037. if (v.z < min.z)
  6038. min.z = v.z;
  6039. if (v.x > max.x)
  6040. max.x = v.x;
  6041. if (v.y > max.y)
  6042. max.y = v.y;
  6043. if (v.z > max.z)
  6044. max.z = v.z;
  6045. };
  6046. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6047. for (var prop in source) {
  6048. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6049. continue;
  6050. }
  6051. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6052. continue;
  6053. }
  6054. var sourceValue = source[prop];
  6055. var typeOfSourceValue = typeof sourceValue;
  6056. if (typeOfSourceValue === "function") {
  6057. continue;
  6058. }
  6059. if (typeOfSourceValue === "object") {
  6060. if (sourceValue instanceof Array) {
  6061. destination[prop] = [];
  6062. if (sourceValue.length > 0) {
  6063. if (typeof sourceValue[0] == "object") {
  6064. for (var index = 0; index < sourceValue.length; index++) {
  6065. var clonedValue = cloneValue(sourceValue[index], destination);
  6066. if (destination[prop].indexOf(clonedValue) === -1) {
  6067. destination[prop].push(clonedValue);
  6068. }
  6069. }
  6070. }
  6071. else {
  6072. destination[prop] = sourceValue.slice(0);
  6073. }
  6074. }
  6075. }
  6076. else {
  6077. destination[prop] = cloneValue(sourceValue, destination);
  6078. }
  6079. }
  6080. else {
  6081. destination[prop] = sourceValue;
  6082. }
  6083. }
  6084. };
  6085. Tools.IsEmpty = function (obj) {
  6086. for (var i in obj) {
  6087. return false;
  6088. }
  6089. return true;
  6090. };
  6091. Tools.RegisterTopRootEvents = function (events) {
  6092. for (var index = 0; index < events.length; index++) {
  6093. var event = events[index];
  6094. window.addEventListener(event.name, event.handler, false);
  6095. try {
  6096. if (window.parent) {
  6097. window.parent.addEventListener(event.name, event.handler, false);
  6098. }
  6099. }
  6100. catch (e) {
  6101. // Silently fails...
  6102. }
  6103. }
  6104. };
  6105. Tools.UnregisterTopRootEvents = function (events) {
  6106. for (var index = 0; index < events.length; index++) {
  6107. var event = events[index];
  6108. window.removeEventListener(event.name, event.handler);
  6109. try {
  6110. if (window.parent) {
  6111. window.parent.removeEventListener(event.name, event.handler);
  6112. }
  6113. }
  6114. catch (e) {
  6115. // Silently fails...
  6116. }
  6117. }
  6118. };
  6119. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6120. if (mimeType === void 0) { mimeType = "image/png"; }
  6121. // Read the contents of the framebuffer
  6122. var numberOfChannelsByLine = width * 4;
  6123. var halfHeight = height / 2;
  6124. //Reading datas from WebGL
  6125. var data = engine.readPixels(0, 0, width, height);
  6126. //To flip image on Y axis.
  6127. for (var i = 0; i < halfHeight; i++) {
  6128. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6129. var currentCell = j + i * numberOfChannelsByLine;
  6130. var targetLine = height - i - 1;
  6131. var targetCell = j + targetLine * numberOfChannelsByLine;
  6132. var temp = data[currentCell];
  6133. data[currentCell] = data[targetCell];
  6134. data[targetCell] = temp;
  6135. }
  6136. }
  6137. // Create a 2D canvas to store the result
  6138. if (!screenshotCanvas) {
  6139. screenshotCanvas = document.createElement('canvas');
  6140. }
  6141. screenshotCanvas.width = width;
  6142. screenshotCanvas.height = height;
  6143. var context = screenshotCanvas.getContext('2d');
  6144. // Copy the pixels to a 2D canvas
  6145. var imageData = context.createImageData(width, height);
  6146. var castData = (imageData.data);
  6147. castData.set(data);
  6148. context.putImageData(imageData, 0, 0);
  6149. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6150. };
  6151. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6152. if (mimeType === void 0) { mimeType = "image/png"; }
  6153. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6154. if (successCallback) {
  6155. successCallback(base64Image);
  6156. }
  6157. else {
  6158. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6159. if (("download" in document.createElement("a"))) {
  6160. var a = window.document.createElement("a");
  6161. a.href = base64Image;
  6162. var date = new Date();
  6163. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6164. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6165. window.document.body.appendChild(a);
  6166. a.addEventListener("click", function () {
  6167. a.parentElement.removeChild(a);
  6168. });
  6169. a.click();
  6170. //Or opening a new tab with the image if it is not possible to automatically start download.
  6171. }
  6172. else {
  6173. var newWindow = window.open("");
  6174. var img = newWindow.document.createElement("img");
  6175. img.src = base64Image;
  6176. newWindow.document.body.appendChild(img);
  6177. }
  6178. }
  6179. };
  6180. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6181. if (mimeType === void 0) { mimeType = "image/png"; }
  6182. var width;
  6183. var height;
  6184. // If a precision value is specified
  6185. if (size.precision) {
  6186. width = Math.round(engine.getRenderWidth() * size.precision);
  6187. height = Math.round(width / engine.getAspectRatio(camera));
  6188. }
  6189. else if (size.width && size.height) {
  6190. width = size.width;
  6191. height = size.height;
  6192. }
  6193. else if (size.width && !size.height) {
  6194. width = size.width;
  6195. height = Math.round(width / engine.getAspectRatio(camera));
  6196. }
  6197. else if (size.height && !size.width) {
  6198. height = size.height;
  6199. width = Math.round(height * engine.getAspectRatio(camera));
  6200. }
  6201. else if (!isNaN(size)) {
  6202. height = size;
  6203. width = size;
  6204. }
  6205. else {
  6206. Tools.Error("Invalid 'size' parameter !");
  6207. return;
  6208. }
  6209. if (!screenshotCanvas) {
  6210. screenshotCanvas = document.createElement('canvas');
  6211. }
  6212. screenshotCanvas.width = width;
  6213. screenshotCanvas.height = height;
  6214. var renderContext = screenshotCanvas.getContext("2d");
  6215. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6216. var newWidth = width;
  6217. var newHeight = newWidth / ratio;
  6218. if (newHeight > height) {
  6219. newHeight = height;
  6220. newWidth = newHeight * ratio;
  6221. }
  6222. var offsetX = Math.max(0, width - newWidth) / 2;
  6223. var offsetY = Math.max(0, height - newHeight) / 2;
  6224. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6225. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6226. };
  6227. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6228. if (mimeType === void 0) { mimeType = "image/png"; }
  6229. if (samples === void 0) { samples = 1; }
  6230. var width;
  6231. var height;
  6232. //If a precision value is specified
  6233. if (size.precision) {
  6234. width = Math.round(engine.getRenderWidth() * size.precision);
  6235. height = Math.round(width / engine.getAspectRatio(camera));
  6236. size = { width: width, height: height };
  6237. }
  6238. else if (size.width && size.height) {
  6239. width = size.width;
  6240. height = size.height;
  6241. }
  6242. else if (size.width && !size.height) {
  6243. width = size.width;
  6244. height = Math.round(width / engine.getAspectRatio(camera));
  6245. size = { width: width, height: height };
  6246. }
  6247. else if (size.height && !size.width) {
  6248. height = size.height;
  6249. width = Math.round(height * engine.getAspectRatio(camera));
  6250. size = { width: width, height: height };
  6251. }
  6252. else if (!isNaN(size)) {
  6253. height = size;
  6254. width = size;
  6255. }
  6256. else {
  6257. Tools.Error("Invalid 'size' parameter !");
  6258. return;
  6259. }
  6260. var scene = camera.getScene();
  6261. var previousCamera = null;
  6262. if (scene.activeCamera !== camera) {
  6263. previousCamera = scene.activeCamera;
  6264. scene.activeCamera = camera;
  6265. }
  6266. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6267. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6268. texture.renderList = null;
  6269. texture.samples = samples;
  6270. texture.onAfterRenderObservable.add(function () {
  6271. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6272. });
  6273. scene.incrementRenderId();
  6274. scene.resetCachedMaterial();
  6275. texture.render(true);
  6276. texture.dispose();
  6277. if (previousCamera) {
  6278. scene.activeCamera = previousCamera;
  6279. }
  6280. camera.getProjectionMatrix(true); // Force cache refresh;
  6281. };
  6282. // XHR response validator for local file scenario
  6283. Tools.ValidateXHRData = function (xhr, dataType) {
  6284. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6285. if (dataType === void 0) { dataType = 7; }
  6286. try {
  6287. if (dataType & 1) {
  6288. if (xhr.responseText && xhr.responseText.length > 0) {
  6289. return true;
  6290. }
  6291. else if (dataType === 1) {
  6292. return false;
  6293. }
  6294. }
  6295. if (dataType & 2) {
  6296. // Check header width and height since there is no "TGA" magic number
  6297. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6298. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6299. return true;
  6300. }
  6301. else if (dataType === 2) {
  6302. return false;
  6303. }
  6304. }
  6305. if (dataType & 4) {
  6306. // Check for the "DDS" magic number
  6307. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6308. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6309. return true;
  6310. }
  6311. else {
  6312. return false;
  6313. }
  6314. }
  6315. }
  6316. catch (e) {
  6317. // Global protection
  6318. }
  6319. return false;
  6320. };
  6321. /**
  6322. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6323. * Be aware Math.random() could cause collisions, but:
  6324. * "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"
  6325. */
  6326. Tools.RandomId = function () {
  6327. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6328. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6329. return v.toString(16);
  6330. });
  6331. };
  6332. Object.defineProperty(Tools, "NoneLogLevel", {
  6333. get: function () {
  6334. return Tools._NoneLogLevel;
  6335. },
  6336. enumerable: true,
  6337. configurable: true
  6338. });
  6339. Object.defineProperty(Tools, "MessageLogLevel", {
  6340. get: function () {
  6341. return Tools._MessageLogLevel;
  6342. },
  6343. enumerable: true,
  6344. configurable: true
  6345. });
  6346. Object.defineProperty(Tools, "WarningLogLevel", {
  6347. get: function () {
  6348. return Tools._WarningLogLevel;
  6349. },
  6350. enumerable: true,
  6351. configurable: true
  6352. });
  6353. Object.defineProperty(Tools, "ErrorLogLevel", {
  6354. get: function () {
  6355. return Tools._ErrorLogLevel;
  6356. },
  6357. enumerable: true,
  6358. configurable: true
  6359. });
  6360. Object.defineProperty(Tools, "AllLogLevel", {
  6361. get: function () {
  6362. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6363. },
  6364. enumerable: true,
  6365. configurable: true
  6366. });
  6367. Tools._AddLogEntry = function (entry) {
  6368. Tools._LogCache = entry + Tools._LogCache;
  6369. if (Tools.OnNewCacheEntry) {
  6370. Tools.OnNewCacheEntry(entry);
  6371. }
  6372. };
  6373. Tools._FormatMessage = function (message) {
  6374. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6375. var date = new Date();
  6376. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6377. };
  6378. Tools._LogDisabled = function (message) {
  6379. // nothing to do
  6380. };
  6381. Tools._LogEnabled = function (message) {
  6382. var formattedMessage = Tools._FormatMessage(message);
  6383. console.log("BJS - " + formattedMessage);
  6384. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6385. Tools._AddLogEntry(entry);
  6386. };
  6387. Tools._WarnDisabled = function (message) {
  6388. // nothing to do
  6389. };
  6390. Tools._WarnEnabled = function (message) {
  6391. var formattedMessage = Tools._FormatMessage(message);
  6392. console.warn("BJS - " + formattedMessage);
  6393. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6394. Tools._AddLogEntry(entry);
  6395. };
  6396. Tools._ErrorDisabled = function (message) {
  6397. // nothing to do
  6398. };
  6399. Tools._ErrorEnabled = function (message) {
  6400. Tools.errorsCount++;
  6401. var formattedMessage = Tools._FormatMessage(message);
  6402. console.error("BJS - " + formattedMessage);
  6403. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6404. Tools._AddLogEntry(entry);
  6405. };
  6406. Object.defineProperty(Tools, "LogCache", {
  6407. get: function () {
  6408. return Tools._LogCache;
  6409. },
  6410. enumerable: true,
  6411. configurable: true
  6412. });
  6413. Tools.ClearLogCache = function () {
  6414. Tools._LogCache = "";
  6415. Tools.errorsCount = 0;
  6416. };
  6417. Object.defineProperty(Tools, "LogLevels", {
  6418. set: function (level) {
  6419. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6420. Tools.Log = Tools._LogEnabled;
  6421. }
  6422. else {
  6423. Tools.Log = Tools._LogDisabled;
  6424. }
  6425. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6426. Tools.Warn = Tools._WarnEnabled;
  6427. }
  6428. else {
  6429. Tools.Warn = Tools._WarnDisabled;
  6430. }
  6431. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6432. Tools.Error = Tools._ErrorEnabled;
  6433. }
  6434. else {
  6435. Tools.Error = Tools._ErrorDisabled;
  6436. }
  6437. },
  6438. enumerable: true,
  6439. configurable: true
  6440. });
  6441. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6442. get: function () {
  6443. return Tools._PerformanceNoneLogLevel;
  6444. },
  6445. enumerable: true,
  6446. configurable: true
  6447. });
  6448. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6449. get: function () {
  6450. return Tools._PerformanceUserMarkLogLevel;
  6451. },
  6452. enumerable: true,
  6453. configurable: true
  6454. });
  6455. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6456. get: function () {
  6457. return Tools._PerformanceConsoleLogLevel;
  6458. },
  6459. enumerable: true,
  6460. configurable: true
  6461. });
  6462. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6463. set: function (level) {
  6464. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6465. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6466. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6467. return;
  6468. }
  6469. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6470. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6471. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6472. return;
  6473. }
  6474. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6475. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6476. },
  6477. enumerable: true,
  6478. configurable: true
  6479. });
  6480. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6481. };
  6482. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6483. };
  6484. Tools._StartUserMark = function (counterName, condition) {
  6485. if (condition === void 0) { condition = true; }
  6486. if (!condition || !Tools._performance.mark) {
  6487. return;
  6488. }
  6489. Tools._performance.mark(counterName + "-Begin");
  6490. };
  6491. Tools._EndUserMark = function (counterName, condition) {
  6492. if (condition === void 0) { condition = true; }
  6493. if (!condition || !Tools._performance.mark) {
  6494. return;
  6495. }
  6496. Tools._performance.mark(counterName + "-End");
  6497. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6498. };
  6499. Tools._StartPerformanceConsole = function (counterName, condition) {
  6500. if (condition === void 0) { condition = true; }
  6501. if (!condition) {
  6502. return;
  6503. }
  6504. Tools._StartUserMark(counterName, condition);
  6505. if (console.time) {
  6506. console.time(counterName);
  6507. }
  6508. };
  6509. Tools._EndPerformanceConsole = function (counterName, condition) {
  6510. if (condition === void 0) { condition = true; }
  6511. if (!condition) {
  6512. return;
  6513. }
  6514. Tools._EndUserMark(counterName, condition);
  6515. if (console.time) {
  6516. console.timeEnd(counterName);
  6517. }
  6518. };
  6519. Object.defineProperty(Tools, "Now", {
  6520. get: function () {
  6521. if (window.performance && window.performance.now) {
  6522. return window.performance.now();
  6523. }
  6524. return new Date().getTime();
  6525. },
  6526. enumerable: true,
  6527. configurable: true
  6528. });
  6529. /**
  6530. * This method will return the name of the class used to create the instance of the given object.
  6531. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6532. * @param object the object to get the class name from
  6533. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6534. */
  6535. Tools.GetClassName = function (object, isType) {
  6536. if (isType === void 0) { isType = false; }
  6537. var name = null;
  6538. if (!isType && object.getClassName) {
  6539. name = object.getClassName();
  6540. }
  6541. else {
  6542. if (object instanceof Object) {
  6543. var classObj = isType ? object : Object.getPrototypeOf(object);
  6544. name = classObj.constructor["__bjsclassName__"];
  6545. }
  6546. if (!name) {
  6547. name = typeof object;
  6548. }
  6549. }
  6550. return name;
  6551. };
  6552. Tools.first = function (array, predicate) {
  6553. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6554. var el = array_1[_i];
  6555. if (predicate(el)) {
  6556. return el;
  6557. }
  6558. }
  6559. };
  6560. /**
  6561. * This method will return the name of the full name of the class, including its owning module (if any).
  6562. * 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).
  6563. * @param object the object to get the class name from
  6564. * @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.
  6565. */
  6566. Tools.getFullClassName = function (object, isType) {
  6567. if (isType === void 0) { isType = false; }
  6568. var className = null;
  6569. var moduleName = null;
  6570. if (!isType && object.getClassName) {
  6571. className = object.getClassName();
  6572. }
  6573. else {
  6574. if (object instanceof Object) {
  6575. var classObj = isType ? object : Object.getPrototypeOf(object);
  6576. className = classObj.constructor["__bjsclassName__"];
  6577. moduleName = classObj.constructor["__bjsmoduleName__"];
  6578. }
  6579. if (!className) {
  6580. className = typeof object;
  6581. }
  6582. }
  6583. if (!className) {
  6584. return null;
  6585. }
  6586. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6587. };
  6588. /**
  6589. * 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.
  6590. * @param array
  6591. */
  6592. Tools.arrayOrStringFeeder = function (array) {
  6593. return function (index) {
  6594. if (index >= array.length) {
  6595. return null;
  6596. }
  6597. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6598. if (val && val.getHashCode) {
  6599. val = val.getHashCode();
  6600. }
  6601. if (typeof val === "string") {
  6602. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6603. }
  6604. return val;
  6605. };
  6606. };
  6607. /**
  6608. * Compute the hashCode of a stream of number
  6609. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6610. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6611. * @return the hash code computed
  6612. */
  6613. Tools.hashCodeFromStream = function (feeder) {
  6614. // Based from here: http://stackoverflow.com/a/7616484/802124
  6615. var hash = 0;
  6616. var index = 0;
  6617. var chr = feeder(index++);
  6618. while (chr != null) {
  6619. hash = ((hash << 5) - hash) + chr;
  6620. hash |= 0; // Convert to 32bit integer
  6621. chr = feeder(index++);
  6622. }
  6623. return hash;
  6624. };
  6625. Tools.BaseUrl = "";
  6626. Tools.CorsBehavior = "anonymous";
  6627. Tools.UseFallbackTexture = true;
  6628. // Used in case of a texture loading problem
  6629. 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";
  6630. Tools.PreprocessUrl = function (url) {
  6631. return url;
  6632. };
  6633. // Logs
  6634. Tools._NoneLogLevel = 0;
  6635. Tools._MessageLogLevel = 1;
  6636. Tools._WarningLogLevel = 2;
  6637. Tools._ErrorLogLevel = 4;
  6638. Tools._LogCache = "";
  6639. Tools.errorsCount = 0;
  6640. Tools.Log = Tools._LogEnabled;
  6641. Tools.Warn = Tools._WarnEnabled;
  6642. Tools.Error = Tools._ErrorEnabled;
  6643. // Performances
  6644. Tools._PerformanceNoneLogLevel = 0;
  6645. Tools._PerformanceUserMarkLogLevel = 1;
  6646. Tools._PerformanceConsoleLogLevel = 2;
  6647. Tools._performance = window.performance;
  6648. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6649. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6650. return Tools;
  6651. }());
  6652. BABYLON.Tools = Tools;
  6653. /**
  6654. * This class is used to track a performance counter which is number based.
  6655. * The user has access to many properties which give statistics of different nature
  6656. *
  6657. * The implementer can track two kinds of Performance Counter: time and count
  6658. * 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.
  6659. * 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.
  6660. */
  6661. var PerfCounter = (function () {
  6662. function PerfCounter() {
  6663. this._startMonitoringTime = 0;
  6664. this._min = 0;
  6665. this._max = 0;
  6666. this._average = 0;
  6667. this._lastSecAverage = 0;
  6668. this._current = 0;
  6669. this._totalValueCount = 0;
  6670. this._totalAccumulated = 0;
  6671. this._lastSecAccumulated = 0;
  6672. this._lastSecTime = 0;
  6673. this._lastSecValueCount = 0;
  6674. }
  6675. Object.defineProperty(PerfCounter.prototype, "min", {
  6676. /**
  6677. * Returns the smallest value ever
  6678. */
  6679. get: function () {
  6680. return this._min;
  6681. },
  6682. enumerable: true,
  6683. configurable: true
  6684. });
  6685. Object.defineProperty(PerfCounter.prototype, "max", {
  6686. /**
  6687. * Returns the biggest value ever
  6688. */
  6689. get: function () {
  6690. return this._max;
  6691. },
  6692. enumerable: true,
  6693. configurable: true
  6694. });
  6695. Object.defineProperty(PerfCounter.prototype, "average", {
  6696. /**
  6697. * Returns the average value since the performance counter is running
  6698. */
  6699. get: function () {
  6700. return this._average;
  6701. },
  6702. enumerable: true,
  6703. configurable: true
  6704. });
  6705. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6706. /**
  6707. * Returns the average value of the last second the counter was monitored
  6708. */
  6709. get: function () {
  6710. return this._lastSecAverage;
  6711. },
  6712. enumerable: true,
  6713. configurable: true
  6714. });
  6715. Object.defineProperty(PerfCounter.prototype, "current", {
  6716. /**
  6717. * Returns the current value
  6718. */
  6719. get: function () {
  6720. return this._current;
  6721. },
  6722. enumerable: true,
  6723. configurable: true
  6724. });
  6725. Object.defineProperty(PerfCounter.prototype, "total", {
  6726. get: function () {
  6727. return this._totalAccumulated;
  6728. },
  6729. enumerable: true,
  6730. configurable: true
  6731. });
  6732. /**
  6733. * Call this method to start monitoring a new frame.
  6734. * 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.
  6735. */
  6736. PerfCounter.prototype.fetchNewFrame = function () {
  6737. this._totalValueCount++;
  6738. this._current = 0;
  6739. this._lastSecValueCount++;
  6740. };
  6741. /**
  6742. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6743. * @param newCount the count value to add to the monitored count
  6744. * @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.
  6745. */
  6746. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6747. if (!PerfCounter.Enabled) {
  6748. return;
  6749. }
  6750. this._current += newCount;
  6751. if (fetchResult) {
  6752. this._fetchResult();
  6753. }
  6754. };
  6755. /**
  6756. * Start monitoring this performance counter
  6757. */
  6758. PerfCounter.prototype.beginMonitoring = function () {
  6759. if (!PerfCounter.Enabled) {
  6760. return;
  6761. }
  6762. this._startMonitoringTime = Tools.Now;
  6763. };
  6764. /**
  6765. * Compute the time lapsed since the previous beginMonitoring() call.
  6766. * @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
  6767. */
  6768. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6769. if (newFrame === void 0) { newFrame = true; }
  6770. if (!PerfCounter.Enabled) {
  6771. return;
  6772. }
  6773. if (newFrame) {
  6774. this.fetchNewFrame();
  6775. }
  6776. var currentTime = Tools.Now;
  6777. this._current = currentTime - this._startMonitoringTime;
  6778. if (newFrame) {
  6779. this._fetchResult();
  6780. }
  6781. };
  6782. PerfCounter.prototype._fetchResult = function () {
  6783. this._totalAccumulated += this._current;
  6784. this._lastSecAccumulated += this._current;
  6785. // Min/Max update
  6786. this._min = Math.min(this._min, this._current);
  6787. this._max = Math.max(this._max, this._current);
  6788. this._average = this._totalAccumulated / this._totalValueCount;
  6789. // Reset last sec?
  6790. var now = Tools.Now;
  6791. if ((now - this._lastSecTime) > 1000) {
  6792. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6793. this._lastSecTime = now;
  6794. this._lastSecAccumulated = 0;
  6795. this._lastSecValueCount = 0;
  6796. }
  6797. };
  6798. PerfCounter.Enabled = true;
  6799. return PerfCounter;
  6800. }());
  6801. BABYLON.PerfCounter = PerfCounter;
  6802. /**
  6803. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6804. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6805. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6806. * @param name The name of the class, case should be preserved
  6807. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6808. */
  6809. function className(name, module) {
  6810. return function (target) {
  6811. target["__bjsclassName__"] = name;
  6812. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6813. };
  6814. }
  6815. BABYLON.className = className;
  6816. /**
  6817. * An implementation of a loop for asynchronous functions.
  6818. */
  6819. var AsyncLoop = (function () {
  6820. /**
  6821. * Constroctor.
  6822. * @param iterations the number of iterations.
  6823. * @param _fn the function to run each iteration
  6824. * @param _successCallback the callback that will be called upon succesful execution
  6825. * @param offset starting offset.
  6826. */
  6827. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6828. if (offset === void 0) { offset = 0; }
  6829. this.iterations = iterations;
  6830. this._fn = _fn;
  6831. this._successCallback = _successCallback;
  6832. this.index = offset - 1;
  6833. this._done = false;
  6834. }
  6835. /**
  6836. * Execute the next iteration. Must be called after the last iteration was finished.
  6837. */
  6838. AsyncLoop.prototype.executeNext = function () {
  6839. if (!this._done) {
  6840. if (this.index + 1 < this.iterations) {
  6841. ++this.index;
  6842. this._fn(this);
  6843. }
  6844. else {
  6845. this.breakLoop();
  6846. }
  6847. }
  6848. };
  6849. /**
  6850. * Break the loop and run the success callback.
  6851. */
  6852. AsyncLoop.prototype.breakLoop = function () {
  6853. this._done = true;
  6854. this._successCallback();
  6855. };
  6856. /**
  6857. * Helper function
  6858. */
  6859. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6860. if (offset === void 0) { offset = 0; }
  6861. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6862. loop.executeNext();
  6863. return loop;
  6864. };
  6865. /**
  6866. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6867. * @param iterations total number of iterations
  6868. * @param syncedIterations number of synchronous iterations in each async iteration.
  6869. * @param fn the function to call each iteration.
  6870. * @param callback a success call back that will be called when iterating stops.
  6871. * @param breakFunction a break condition (optional)
  6872. * @param timeout timeout settings for the setTimeout function. default - 0.
  6873. * @constructor
  6874. */
  6875. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6876. if (timeout === void 0) { timeout = 0; }
  6877. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6878. if (breakFunction && breakFunction())
  6879. loop.breakLoop();
  6880. else {
  6881. setTimeout(function () {
  6882. for (var i = 0; i < syncedIterations; ++i) {
  6883. var iteration = (loop.index * syncedIterations) + i;
  6884. if (iteration >= iterations)
  6885. break;
  6886. fn(iteration);
  6887. if (breakFunction && breakFunction()) {
  6888. loop.breakLoop();
  6889. break;
  6890. }
  6891. }
  6892. loop.executeNext();
  6893. }, timeout);
  6894. }
  6895. }, callback);
  6896. };
  6897. return AsyncLoop;
  6898. }());
  6899. BABYLON.AsyncLoop = AsyncLoop;
  6900. })(BABYLON || (BABYLON = {}));
  6901. //# sourceMappingURL=babylon.tools.js.map
  6902. var BABYLON;
  6903. (function (BABYLON) {
  6904. var Internals;
  6905. (function (Internals) {
  6906. var _AlphaState = (function () {
  6907. /**
  6908. * Initializes the state.
  6909. */
  6910. function _AlphaState() {
  6911. this._isAlphaBlendDirty = false;
  6912. this._isBlendFunctionParametersDirty = false;
  6913. this._isBlendEquationParametersDirty = false;
  6914. this._isBlendConstantsDirty = false;
  6915. this._alphaBlend = false;
  6916. this._blendFunctionParameters = new Array(4);
  6917. this._blendEquationParameters = new Array(2);
  6918. this._blendConstants = new Array(4);
  6919. this.reset();
  6920. }
  6921. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6922. get: function () {
  6923. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6924. },
  6925. enumerable: true,
  6926. configurable: true
  6927. });
  6928. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6929. get: function () {
  6930. return this._alphaBlend;
  6931. },
  6932. set: function (value) {
  6933. if (this._alphaBlend === value) {
  6934. return;
  6935. }
  6936. this._alphaBlend = value;
  6937. this._isAlphaBlendDirty = true;
  6938. },
  6939. enumerable: true,
  6940. configurable: true
  6941. });
  6942. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6943. if (this._blendConstants[0] === r &&
  6944. this._blendConstants[1] === g &&
  6945. this._blendConstants[2] === b &&
  6946. this._blendConstants[3] === a) {
  6947. return;
  6948. }
  6949. this._blendConstants[0] = r;
  6950. this._blendConstants[1] = g;
  6951. this._blendConstants[2] = b;
  6952. this._blendConstants[3] = a;
  6953. this._isBlendConstantsDirty = true;
  6954. };
  6955. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6956. if (this._blendFunctionParameters[0] === value0 &&
  6957. this._blendFunctionParameters[1] === value1 &&
  6958. this._blendFunctionParameters[2] === value2 &&
  6959. this._blendFunctionParameters[3] === value3) {
  6960. return;
  6961. }
  6962. this._blendFunctionParameters[0] = value0;
  6963. this._blendFunctionParameters[1] = value1;
  6964. this._blendFunctionParameters[2] = value2;
  6965. this._blendFunctionParameters[3] = value3;
  6966. this._isBlendFunctionParametersDirty = true;
  6967. };
  6968. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6969. if (this._blendEquationParameters[0] === rgb &&
  6970. this._blendEquationParameters[1] === alpha) {
  6971. return;
  6972. }
  6973. this._blendEquationParameters[0] = rgb;
  6974. this._blendEquationParameters[1] = alpha;
  6975. this._isBlendEquationParametersDirty = true;
  6976. };
  6977. _AlphaState.prototype.reset = function () {
  6978. this._alphaBlend = false;
  6979. this._blendFunctionParameters[0] = null;
  6980. this._blendFunctionParameters[1] = null;
  6981. this._blendFunctionParameters[2] = null;
  6982. this._blendFunctionParameters[3] = null;
  6983. this._blendEquationParameters[0] = null;
  6984. this._blendEquationParameters[1] = null;
  6985. this._blendConstants[0] = null;
  6986. this._blendConstants[1] = null;
  6987. this._blendConstants[2] = null;
  6988. this._blendConstants[3] = null;
  6989. this._isAlphaBlendDirty = true;
  6990. this._isBlendFunctionParametersDirty = false;
  6991. this._isBlendEquationParametersDirty = false;
  6992. this._isBlendConstantsDirty = false;
  6993. };
  6994. _AlphaState.prototype.apply = function (gl) {
  6995. if (!this.isDirty) {
  6996. return;
  6997. }
  6998. // Alpha blend
  6999. if (this._isAlphaBlendDirty) {
  7000. if (this._alphaBlend) {
  7001. gl.enable(gl.BLEND);
  7002. }
  7003. else {
  7004. gl.disable(gl.BLEND);
  7005. }
  7006. this._isAlphaBlendDirty = false;
  7007. }
  7008. // Alpha function
  7009. if (this._isBlendFunctionParametersDirty) {
  7010. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7011. this._isBlendFunctionParametersDirty = false;
  7012. }
  7013. // Alpha equation
  7014. if (this._isBlendEquationParametersDirty) {
  7015. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7016. this._isBlendEquationParametersDirty = false;
  7017. }
  7018. // Constants
  7019. if (this._isBlendConstantsDirty) {
  7020. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7021. this._isBlendConstantsDirty = false;
  7022. }
  7023. };
  7024. return _AlphaState;
  7025. }());
  7026. Internals._AlphaState = _AlphaState;
  7027. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7028. })(BABYLON || (BABYLON = {}));
  7029. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7030. var BABYLON;
  7031. (function (BABYLON) {
  7032. var Internals;
  7033. (function (Internals) {
  7034. var _DepthCullingState = (function () {
  7035. /**
  7036. * Initializes the state.
  7037. */
  7038. function _DepthCullingState() {
  7039. this._isDepthTestDirty = false;
  7040. this._isDepthMaskDirty = false;
  7041. this._isDepthFuncDirty = false;
  7042. this._isCullFaceDirty = false;
  7043. this._isCullDirty = false;
  7044. this._isZOffsetDirty = false;
  7045. this.reset();
  7046. }
  7047. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7048. get: function () {
  7049. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7050. },
  7051. enumerable: true,
  7052. configurable: true
  7053. });
  7054. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7055. get: function () {
  7056. return this._zOffset;
  7057. },
  7058. set: function (value) {
  7059. if (this._zOffset === value) {
  7060. return;
  7061. }
  7062. this._zOffset = value;
  7063. this._isZOffsetDirty = true;
  7064. },
  7065. enumerable: true,
  7066. configurable: true
  7067. });
  7068. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7069. get: function () {
  7070. return this._cullFace;
  7071. },
  7072. set: function (value) {
  7073. if (this._cullFace === value) {
  7074. return;
  7075. }
  7076. this._cullFace = value;
  7077. this._isCullFaceDirty = true;
  7078. },
  7079. enumerable: true,
  7080. configurable: true
  7081. });
  7082. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7083. get: function () {
  7084. return this._cull;
  7085. },
  7086. set: function (value) {
  7087. if (this._cull === value) {
  7088. return;
  7089. }
  7090. this._cull = value;
  7091. this._isCullDirty = true;
  7092. },
  7093. enumerable: true,
  7094. configurable: true
  7095. });
  7096. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7097. get: function () {
  7098. return this._depthFunc;
  7099. },
  7100. set: function (value) {
  7101. if (this._depthFunc === value) {
  7102. return;
  7103. }
  7104. this._depthFunc = value;
  7105. this._isDepthFuncDirty = true;
  7106. },
  7107. enumerable: true,
  7108. configurable: true
  7109. });
  7110. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7111. get: function () {
  7112. return this._depthMask;
  7113. },
  7114. set: function (value) {
  7115. if (this._depthMask === value) {
  7116. return;
  7117. }
  7118. this._depthMask = value;
  7119. this._isDepthMaskDirty = true;
  7120. },
  7121. enumerable: true,
  7122. configurable: true
  7123. });
  7124. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7125. get: function () {
  7126. return this._depthTest;
  7127. },
  7128. set: function (value) {
  7129. if (this._depthTest === value) {
  7130. return;
  7131. }
  7132. this._depthTest = value;
  7133. this._isDepthTestDirty = true;
  7134. },
  7135. enumerable: true,
  7136. configurable: true
  7137. });
  7138. _DepthCullingState.prototype.reset = function () {
  7139. this._depthMask = true;
  7140. this._depthTest = true;
  7141. this._depthFunc = null;
  7142. this._cullFace = null;
  7143. this._cull = null;
  7144. this._zOffset = 0;
  7145. this._isDepthTestDirty = true;
  7146. this._isDepthMaskDirty = true;
  7147. this._isDepthFuncDirty = false;
  7148. this._isCullFaceDirty = false;
  7149. this._isCullDirty = false;
  7150. this._isZOffsetDirty = false;
  7151. };
  7152. _DepthCullingState.prototype.apply = function (gl) {
  7153. if (!this.isDirty) {
  7154. return;
  7155. }
  7156. // Cull
  7157. if (this._isCullDirty) {
  7158. if (this.cull) {
  7159. gl.enable(gl.CULL_FACE);
  7160. }
  7161. else {
  7162. gl.disable(gl.CULL_FACE);
  7163. }
  7164. this._isCullDirty = false;
  7165. }
  7166. // Cull face
  7167. if (this._isCullFaceDirty) {
  7168. gl.cullFace(this.cullFace);
  7169. this._isCullFaceDirty = false;
  7170. }
  7171. // Depth mask
  7172. if (this._isDepthMaskDirty) {
  7173. gl.depthMask(this.depthMask);
  7174. this._isDepthMaskDirty = false;
  7175. }
  7176. // Depth test
  7177. if (this._isDepthTestDirty) {
  7178. if (this.depthTest) {
  7179. gl.enable(gl.DEPTH_TEST);
  7180. }
  7181. else {
  7182. gl.disable(gl.DEPTH_TEST);
  7183. }
  7184. this._isDepthTestDirty = false;
  7185. }
  7186. // Depth func
  7187. if (this._isDepthFuncDirty) {
  7188. gl.depthFunc(this.depthFunc);
  7189. this._isDepthFuncDirty = false;
  7190. }
  7191. // zOffset
  7192. if (this._isZOffsetDirty) {
  7193. if (this.zOffset) {
  7194. gl.enable(gl.POLYGON_OFFSET_FILL);
  7195. gl.polygonOffset(this.zOffset, 0);
  7196. }
  7197. else {
  7198. gl.disable(gl.POLYGON_OFFSET_FILL);
  7199. }
  7200. this._isZOffsetDirty = false;
  7201. }
  7202. };
  7203. return _DepthCullingState;
  7204. }());
  7205. Internals._DepthCullingState = _DepthCullingState;
  7206. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7207. })(BABYLON || (BABYLON = {}));
  7208. //# sourceMappingURL=babylon.depthCullingState.js.map
  7209. var BABYLON;
  7210. (function (BABYLON) {
  7211. var Internals;
  7212. (function (Internals) {
  7213. var _StencilState = (function () {
  7214. function _StencilState() {
  7215. this._isStencilTestDirty = false;
  7216. this._isStencilMaskDirty = false;
  7217. this._isStencilFuncDirty = false;
  7218. this._isStencilOpDirty = false;
  7219. this.reset();
  7220. }
  7221. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7222. get: function () {
  7223. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7224. },
  7225. enumerable: true,
  7226. configurable: true
  7227. });
  7228. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7229. get: function () {
  7230. return this._stencilFunc;
  7231. },
  7232. set: function (value) {
  7233. if (this._stencilFunc === value) {
  7234. return;
  7235. }
  7236. this._stencilFunc = value;
  7237. this._isStencilFuncDirty = true;
  7238. },
  7239. enumerable: true,
  7240. configurable: true
  7241. });
  7242. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7243. get: function () {
  7244. return this._stencilFuncRef;
  7245. },
  7246. set: function (value) {
  7247. if (this._stencilFuncRef === value) {
  7248. return;
  7249. }
  7250. this._stencilFuncRef = value;
  7251. this._isStencilFuncDirty = true;
  7252. },
  7253. enumerable: true,
  7254. configurable: true
  7255. });
  7256. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7257. get: function () {
  7258. return this._stencilFuncMask;
  7259. },
  7260. set: function (value) {
  7261. if (this._stencilFuncMask === value) {
  7262. return;
  7263. }
  7264. this._stencilFuncMask = value;
  7265. this._isStencilFuncDirty = true;
  7266. },
  7267. enumerable: true,
  7268. configurable: true
  7269. });
  7270. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7271. get: function () {
  7272. return this._stencilOpStencilFail;
  7273. },
  7274. set: function (value) {
  7275. if (this._stencilOpStencilFail === value) {
  7276. return;
  7277. }
  7278. this._stencilOpStencilFail = value;
  7279. this._isStencilOpDirty = true;
  7280. },
  7281. enumerable: true,
  7282. configurable: true
  7283. });
  7284. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7285. get: function () {
  7286. return this._stencilOpDepthFail;
  7287. },
  7288. set: function (value) {
  7289. if (this._stencilOpDepthFail === value) {
  7290. return;
  7291. }
  7292. this._stencilOpDepthFail = value;
  7293. this._isStencilOpDirty = true;
  7294. },
  7295. enumerable: true,
  7296. configurable: true
  7297. });
  7298. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7299. get: function () {
  7300. return this._stencilOpStencilDepthPass;
  7301. },
  7302. set: function (value) {
  7303. if (this._stencilOpStencilDepthPass === value) {
  7304. return;
  7305. }
  7306. this._stencilOpStencilDepthPass = value;
  7307. this._isStencilOpDirty = true;
  7308. },
  7309. enumerable: true,
  7310. configurable: true
  7311. });
  7312. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7313. get: function () {
  7314. return this._stencilMask;
  7315. },
  7316. set: function (value) {
  7317. if (this._stencilMask === value) {
  7318. return;
  7319. }
  7320. this._stencilMask = value;
  7321. this._isStencilMaskDirty = true;
  7322. },
  7323. enumerable: true,
  7324. configurable: true
  7325. });
  7326. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7327. get: function () {
  7328. return this._stencilTest;
  7329. },
  7330. set: function (value) {
  7331. if (this._stencilTest === value) {
  7332. return;
  7333. }
  7334. this._stencilTest = value;
  7335. this._isStencilTestDirty = true;
  7336. },
  7337. enumerable: true,
  7338. configurable: true
  7339. });
  7340. _StencilState.prototype.reset = function () {
  7341. this._stencilTest = false;
  7342. this._stencilMask = 0xFF;
  7343. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7344. this._stencilFuncRef = 1;
  7345. this._stencilFuncMask = 0xFF;
  7346. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7347. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7348. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7349. this._isStencilTestDirty = true;
  7350. this._isStencilMaskDirty = true;
  7351. this._isStencilFuncDirty = true;
  7352. this._isStencilOpDirty = true;
  7353. };
  7354. _StencilState.prototype.apply = function (gl) {
  7355. if (!this.isDirty) {
  7356. return;
  7357. }
  7358. // Stencil test
  7359. if (this._isStencilTestDirty) {
  7360. if (this.stencilTest) {
  7361. gl.enable(gl.STENCIL_TEST);
  7362. }
  7363. else {
  7364. gl.disable(gl.STENCIL_TEST);
  7365. }
  7366. this._isStencilTestDirty = false;
  7367. }
  7368. // Stencil mask
  7369. if (this._isStencilMaskDirty) {
  7370. gl.stencilMask(this.stencilMask);
  7371. this._isStencilMaskDirty = false;
  7372. }
  7373. // Stencil func
  7374. if (this._isStencilFuncDirty) {
  7375. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7376. this._isStencilFuncDirty = false;
  7377. }
  7378. // Stencil op
  7379. if (this._isStencilOpDirty) {
  7380. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7381. this._isStencilOpDirty = false;
  7382. }
  7383. };
  7384. return _StencilState;
  7385. }());
  7386. Internals._StencilState = _StencilState;
  7387. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7388. })(BABYLON || (BABYLON = {}));
  7389. //# sourceMappingURL=babylon.stencilState.js.map
  7390. var BABYLON;
  7391. (function (BABYLON) {
  7392. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7393. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7394. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7395. gl.compileShader(shader);
  7396. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7397. throw new Error(gl.getShaderInfoLog(shader));
  7398. }
  7399. return shader;
  7400. };
  7401. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7402. var magFilter = gl.NEAREST;
  7403. var minFilter = gl.NEAREST;
  7404. switch (samplingMode) {
  7405. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7406. magFilter = gl.LINEAR;
  7407. if (generateMipMaps) {
  7408. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7409. }
  7410. else {
  7411. minFilter = gl.LINEAR;
  7412. }
  7413. break;
  7414. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7415. magFilter = gl.LINEAR;
  7416. if (generateMipMaps) {
  7417. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7418. }
  7419. else {
  7420. minFilter = gl.LINEAR;
  7421. }
  7422. break;
  7423. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7424. magFilter = gl.NEAREST;
  7425. if (generateMipMaps) {
  7426. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7427. }
  7428. else {
  7429. minFilter = gl.NEAREST;
  7430. }
  7431. break;
  7432. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7433. magFilter = gl.NEAREST;
  7434. if (generateMipMaps) {
  7435. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7436. }
  7437. else {
  7438. minFilter = gl.NEAREST;
  7439. }
  7440. break;
  7441. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7442. magFilter = gl.NEAREST;
  7443. if (generateMipMaps) {
  7444. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7445. }
  7446. else {
  7447. minFilter = gl.LINEAR;
  7448. }
  7449. break;
  7450. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7451. magFilter = gl.NEAREST;
  7452. if (generateMipMaps) {
  7453. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7454. }
  7455. else {
  7456. minFilter = gl.LINEAR;
  7457. }
  7458. break;
  7459. case BABYLON.Texture.NEAREST_LINEAR:
  7460. magFilter = gl.NEAREST;
  7461. minFilter = gl.LINEAR;
  7462. break;
  7463. case BABYLON.Texture.NEAREST_NEAREST:
  7464. magFilter = gl.NEAREST;
  7465. minFilter = gl.NEAREST;
  7466. break;
  7467. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7468. magFilter = gl.LINEAR;
  7469. if (generateMipMaps) {
  7470. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7471. }
  7472. else {
  7473. minFilter = gl.NEAREST;
  7474. }
  7475. break;
  7476. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7477. magFilter = gl.LINEAR;
  7478. if (generateMipMaps) {
  7479. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7480. }
  7481. else {
  7482. minFilter = gl.NEAREST;
  7483. }
  7484. break;
  7485. case BABYLON.Texture.LINEAR_LINEAR:
  7486. magFilter = gl.LINEAR;
  7487. minFilter = gl.LINEAR;
  7488. break;
  7489. case BABYLON.Texture.LINEAR_NEAREST:
  7490. magFilter = gl.LINEAR;
  7491. minFilter = gl.NEAREST;
  7492. break;
  7493. }
  7494. return {
  7495. min: minFilter,
  7496. mag: magFilter
  7497. };
  7498. };
  7499. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7500. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7501. var img;
  7502. var onload = function () {
  7503. loadedImages[index] = img;
  7504. loadedImages._internalCount++;
  7505. if (scene) {
  7506. scene._removePendingData(img);
  7507. }
  7508. if (loadedImages._internalCount === 6) {
  7509. onfinish(loadedImages);
  7510. }
  7511. };
  7512. var onerror = function () {
  7513. if (scene) {
  7514. scene._removePendingData(img);
  7515. }
  7516. if (onErrorCallBack) {
  7517. onErrorCallBack();
  7518. }
  7519. };
  7520. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7521. if (scene) {
  7522. scene._addPendingData(img);
  7523. }
  7524. };
  7525. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7526. if (onError === void 0) { onError = null; }
  7527. var loadedImages = [];
  7528. loadedImages._internalCount = 0;
  7529. for (var index = 0; index < 6; index++) {
  7530. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7531. }
  7532. };
  7533. var BufferPointer = (function () {
  7534. function BufferPointer() {
  7535. }
  7536. return BufferPointer;
  7537. }());
  7538. var InstancingAttributeInfo = (function () {
  7539. function InstancingAttributeInfo() {
  7540. }
  7541. return InstancingAttributeInfo;
  7542. }());
  7543. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7544. /**
  7545. * Define options used to create a render target texture
  7546. */
  7547. var RenderTargetCreationOptions = (function () {
  7548. function RenderTargetCreationOptions() {
  7549. }
  7550. return RenderTargetCreationOptions;
  7551. }());
  7552. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7553. /**
  7554. * Regroup several parameters relative to the browser in use
  7555. */
  7556. var EngineCapabilities = (function () {
  7557. function EngineCapabilities() {
  7558. }
  7559. return EngineCapabilities;
  7560. }());
  7561. BABYLON.EngineCapabilities = EngineCapabilities;
  7562. /**
  7563. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7564. */
  7565. var Engine = (function () {
  7566. /**
  7567. * @constructor
  7568. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7569. * @param {boolean} [antialias] - enable antialias
  7570. * @param options - further options to be sent to the getContext function
  7571. */
  7572. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7573. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7574. var _this = this;
  7575. // Public members
  7576. this.forcePOTTextures = false;
  7577. this.isFullscreen = false;
  7578. this.isPointerLock = false;
  7579. this.cullBackFaces = true;
  7580. this.renderEvenInBackground = true;
  7581. this.preventCacheWipeBetweenFrames = false;
  7582. // To enable/disable IDB support and avoid XHR on .manifest
  7583. this.enableOfflineSupport = false;
  7584. this.scenes = new Array();
  7585. this.postProcesses = new Array();
  7586. // Observables
  7587. /**
  7588. * Observable event triggered each time the rendering canvas is resized
  7589. */
  7590. this.onResizeObservable = new BABYLON.Observable();
  7591. /**
  7592. * Observable event triggered each time the canvas loses focus
  7593. */
  7594. this.onCanvasBlurObservable = new BABYLON.Observable();
  7595. /**
  7596. * Observable event triggered each time the canvas gains focus
  7597. */
  7598. this.onCanvasFocusObservable = new BABYLON.Observable();
  7599. /**
  7600. * Observable event triggered each time the canvas receives pointerout event
  7601. */
  7602. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7603. // Uniform buffers list
  7604. this.disableUniformBuffers = false;
  7605. this._uniformBuffers = new Array();
  7606. this._windowIsBackground = false;
  7607. this._webGLVersion = 1.0;
  7608. this._badOS = false;
  7609. this._badDesktopOS = false;
  7610. this._drawCalls = new BABYLON.PerfCounter();
  7611. this._renderingQueueLaunched = false;
  7612. this._activeRenderLoops = [];
  7613. // Deterministic lockstepMaxSteps
  7614. this._deterministicLockstep = false;
  7615. this._lockstepMaxSteps = 4;
  7616. // Lost context
  7617. this.onContextLostObservable = new BABYLON.Observable();
  7618. this.onContextRestoredObservable = new BABYLON.Observable();
  7619. this._contextWasLost = false;
  7620. this._doNotHandleContextLost = false;
  7621. // FPS
  7622. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7623. this._fps = 60;
  7624. this._deltaTime = 0;
  7625. /**
  7626. * Turn this value on if you want to pause FPS computation when in background
  7627. */
  7628. this.disablePerformanceMonitorInBackground = false;
  7629. // States
  7630. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7631. this._stencilState = new BABYLON.Internals._StencilState();
  7632. this._alphaState = new BABYLON.Internals._AlphaState();
  7633. this._alphaMode = Engine.ALPHA_DISABLE;
  7634. // Cache
  7635. this._internalTexturesCache = new Array();
  7636. this._maxTextureChannels = 16;
  7637. this._activeTexturesCache = {};
  7638. this._compiledEffects = {};
  7639. this._vertexAttribArraysEnabled = [];
  7640. this._uintIndicesCurrentlySet = false;
  7641. this._currentBoundBuffer = new Array();
  7642. this._currentBufferPointers = new Array();
  7643. this._currentInstanceLocations = new Array();
  7644. this._currentInstanceBuffers = new Array();
  7645. this._vaoRecordInProgress = false;
  7646. this._mustWipeVertexAttributes = false;
  7647. // Hardware supported Compressed Textures
  7648. this._texturesSupported = new Array();
  7649. this._onVRFullScreenTriggered = function () {
  7650. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7651. //get the old size before we change
  7652. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7653. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7654. //get the width and height, change the render size
  7655. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7656. var width, height;
  7657. _this.setHardwareScalingLevel(1);
  7658. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7659. }
  7660. else {
  7661. //When the specs are implemented, need to uncomment this.
  7662. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7663. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7664. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7665. _this._vrDisplayEnabled = undefined;
  7666. }
  7667. };
  7668. var canvas;
  7669. Engine.Instances.push(this);
  7670. options = options || {};
  7671. if (canvasOrContext.getContext) {
  7672. canvas = canvasOrContext;
  7673. this._renderingCanvas = canvas;
  7674. if (antialias != null) {
  7675. options.antialias = antialias;
  7676. }
  7677. if (options.deterministicLockstep === undefined) {
  7678. options.deterministicLockstep = false;
  7679. }
  7680. if (options.lockstepMaxSteps === undefined) {
  7681. options.lockstepMaxSteps = 4;
  7682. }
  7683. if (options.preserveDrawingBuffer === undefined) {
  7684. options.preserveDrawingBuffer = false;
  7685. }
  7686. if (options.audioEngine === undefined) {
  7687. options.audioEngine = true;
  7688. }
  7689. if (options.stencil === undefined) {
  7690. options.stencil = true;
  7691. }
  7692. this._deterministicLockstep = options.deterministicLockstep;
  7693. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7694. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7695. // GL
  7696. if (!options.disableWebGL2Support) {
  7697. try {
  7698. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7699. if (this._gl) {
  7700. this._webGLVersion = 2.0;
  7701. }
  7702. }
  7703. catch (e) {
  7704. // Do nothing
  7705. }
  7706. }
  7707. if (!this._gl) {
  7708. if (!canvas) {
  7709. throw new Error("The provided canvas is null or undefined.");
  7710. }
  7711. try {
  7712. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7713. }
  7714. catch (e) {
  7715. throw new Error("WebGL not supported");
  7716. }
  7717. }
  7718. if (!this._gl) {
  7719. throw new Error("WebGL not supported");
  7720. }
  7721. this._onCanvasFocus = function () {
  7722. _this.onCanvasFocusObservable.notifyObservers(_this);
  7723. };
  7724. this._onCanvasBlur = function () {
  7725. _this.onCanvasBlurObservable.notifyObservers(_this);
  7726. };
  7727. canvas.addEventListener("focus", this._onCanvasFocus);
  7728. canvas.addEventListener("blur", this._onCanvasBlur);
  7729. this._onBlur = function () {
  7730. if (_this.disablePerformanceMonitorInBackground) {
  7731. _this._performanceMonitor.disable();
  7732. }
  7733. _this._windowIsBackground = true;
  7734. };
  7735. this._onFocus = function () {
  7736. if (_this.disablePerformanceMonitorInBackground) {
  7737. _this._performanceMonitor.enable();
  7738. }
  7739. _this._windowIsBackground = false;
  7740. };
  7741. this._onCanvasPointerOut = function () {
  7742. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7743. };
  7744. window.addEventListener("blur", this._onBlur);
  7745. window.addEventListener("focus", this._onFocus);
  7746. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  7747. }
  7748. else {
  7749. this._gl = canvasOrContext;
  7750. this._renderingCanvas = this._gl.canvas;
  7751. if (this._gl.renderbufferStorageMultisample) {
  7752. this._webGLVersion = 2.0;
  7753. }
  7754. options.stencil = this._gl.getContextAttributes().stencil;
  7755. }
  7756. // Context lost
  7757. if (!this._doNotHandleContextLost) {
  7758. this._onContextLost = function (evt) {
  7759. evt.preventDefault();
  7760. _this._contextWasLost = true;
  7761. BABYLON.Tools.Warn("WebGL context lost.");
  7762. _this.onContextLostObservable.notifyObservers(_this);
  7763. };
  7764. this._onContextRestored = function (evt) {
  7765. // Rebuild gl context
  7766. _this._initGLContext();
  7767. // Rebuild effects
  7768. _this._rebuildEffects();
  7769. // Rebuild textures
  7770. _this._rebuildInternalTextures();
  7771. // Rebuild buffers
  7772. _this._rebuildBuffers();
  7773. // Cache
  7774. _this.wipeCaches(true);
  7775. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7776. _this.onContextRestoredObservable.notifyObservers(_this);
  7777. _this._contextWasLost = false;
  7778. };
  7779. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7780. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7781. }
  7782. // Viewport
  7783. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7784. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7785. this.resize();
  7786. this._isStencilEnable = options.stencil;
  7787. this._initGLContext();
  7788. if (canvas) {
  7789. // Fullscreen
  7790. this._onFullscreenChange = function () {
  7791. if (document.fullscreen !== undefined) {
  7792. _this.isFullscreen = document.fullscreen;
  7793. }
  7794. else if (document.mozFullScreen !== undefined) {
  7795. _this.isFullscreen = document.mozFullScreen;
  7796. }
  7797. else if (document.webkitIsFullScreen !== undefined) {
  7798. _this.isFullscreen = document.webkitIsFullScreen;
  7799. }
  7800. else if (document.msIsFullScreen !== undefined) {
  7801. _this.isFullscreen = document.msIsFullScreen;
  7802. }
  7803. // Pointer lock
  7804. if (_this.isFullscreen && _this._pointerLockRequested) {
  7805. canvas.requestPointerLock = canvas.requestPointerLock ||
  7806. canvas.msRequestPointerLock ||
  7807. canvas.mozRequestPointerLock ||
  7808. canvas.webkitRequestPointerLock;
  7809. if (canvas.requestPointerLock) {
  7810. canvas.requestPointerLock();
  7811. }
  7812. }
  7813. };
  7814. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7815. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7816. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7817. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7818. // Pointer lock
  7819. this._onPointerLockChange = function () {
  7820. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7821. document.webkitPointerLockElement === canvas ||
  7822. document.msPointerLockElement === canvas ||
  7823. document.pointerLockElement === canvas);
  7824. };
  7825. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7826. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7827. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7828. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7829. this._onVRDisplayPointerRestricted = function () {
  7830. canvas.requestPointerLock();
  7831. };
  7832. this._onVRDisplayPointerUnrestricted = function () {
  7833. document.exitPointerLock();
  7834. };
  7835. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7836. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7837. }
  7838. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7839. Engine.audioEngine = new BABYLON.AudioEngine();
  7840. }
  7841. // Prepare buffer pointers
  7842. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7843. this._currentBufferPointers[i] = new BufferPointer();
  7844. }
  7845. // Load WebVR Devices
  7846. if (options.autoEnableWebVR) {
  7847. this.initWebVR();
  7848. }
  7849. // Detect if we are running on a faulty buggy OS.
  7850. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7851. // Detect if we are running on a faulty buggy desktop OS.
  7852. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7853. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7854. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7855. }
  7856. Object.defineProperty(Engine, "LastCreatedEngine", {
  7857. get: function () {
  7858. if (Engine.Instances.length === 0) {
  7859. return null;
  7860. }
  7861. return Engine.Instances[Engine.Instances.length - 1];
  7862. },
  7863. enumerable: true,
  7864. configurable: true
  7865. });
  7866. Object.defineProperty(Engine, "LastCreatedScene", {
  7867. get: function () {
  7868. var lastCreatedEngine = Engine.LastCreatedEngine;
  7869. if (!lastCreatedEngine) {
  7870. return null;
  7871. }
  7872. if (lastCreatedEngine.scenes.length === 0) {
  7873. return null;
  7874. }
  7875. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7876. },
  7877. enumerable: true,
  7878. configurable: true
  7879. });
  7880. /**
  7881. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7882. */
  7883. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7884. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7885. var engine = Engine.Instances[engineIndex];
  7886. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7887. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7888. }
  7889. }
  7890. };
  7891. Object.defineProperty(Engine, "NEVER", {
  7892. get: function () {
  7893. return Engine._NEVER;
  7894. },
  7895. enumerable: true,
  7896. configurable: true
  7897. });
  7898. Object.defineProperty(Engine, "ALWAYS", {
  7899. get: function () {
  7900. return Engine._ALWAYS;
  7901. },
  7902. enumerable: true,
  7903. configurable: true
  7904. });
  7905. Object.defineProperty(Engine, "LESS", {
  7906. get: function () {
  7907. return Engine._LESS;
  7908. },
  7909. enumerable: true,
  7910. configurable: true
  7911. });
  7912. Object.defineProperty(Engine, "EQUAL", {
  7913. get: function () {
  7914. return Engine._EQUAL;
  7915. },
  7916. enumerable: true,
  7917. configurable: true
  7918. });
  7919. Object.defineProperty(Engine, "LEQUAL", {
  7920. get: function () {
  7921. return Engine._LEQUAL;
  7922. },
  7923. enumerable: true,
  7924. configurable: true
  7925. });
  7926. Object.defineProperty(Engine, "GREATER", {
  7927. get: function () {
  7928. return Engine._GREATER;
  7929. },
  7930. enumerable: true,
  7931. configurable: true
  7932. });
  7933. Object.defineProperty(Engine, "GEQUAL", {
  7934. get: function () {
  7935. return Engine._GEQUAL;
  7936. },
  7937. enumerable: true,
  7938. configurable: true
  7939. });
  7940. Object.defineProperty(Engine, "NOTEQUAL", {
  7941. get: function () {
  7942. return Engine._NOTEQUAL;
  7943. },
  7944. enumerable: true,
  7945. configurable: true
  7946. });
  7947. Object.defineProperty(Engine, "KEEP", {
  7948. get: function () {
  7949. return Engine._KEEP;
  7950. },
  7951. enumerable: true,
  7952. configurable: true
  7953. });
  7954. Object.defineProperty(Engine, "REPLACE", {
  7955. get: function () {
  7956. return Engine._REPLACE;
  7957. },
  7958. enumerable: true,
  7959. configurable: true
  7960. });
  7961. Object.defineProperty(Engine, "INCR", {
  7962. get: function () {
  7963. return Engine._INCR;
  7964. },
  7965. enumerable: true,
  7966. configurable: true
  7967. });
  7968. Object.defineProperty(Engine, "DECR", {
  7969. get: function () {
  7970. return Engine._DECR;
  7971. },
  7972. enumerable: true,
  7973. configurable: true
  7974. });
  7975. Object.defineProperty(Engine, "INVERT", {
  7976. get: function () {
  7977. return Engine._INVERT;
  7978. },
  7979. enumerable: true,
  7980. configurable: true
  7981. });
  7982. Object.defineProperty(Engine, "INCR_WRAP", {
  7983. get: function () {
  7984. return Engine._INCR_WRAP;
  7985. },
  7986. enumerable: true,
  7987. configurable: true
  7988. });
  7989. Object.defineProperty(Engine, "DECR_WRAP", {
  7990. get: function () {
  7991. return Engine._DECR_WRAP;
  7992. },
  7993. enumerable: true,
  7994. configurable: true
  7995. });
  7996. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7997. get: function () {
  7998. return Engine._ALPHA_DISABLE;
  7999. },
  8000. enumerable: true,
  8001. configurable: true
  8002. });
  8003. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8004. get: function () {
  8005. return Engine._ALPHA_ONEONE;
  8006. },
  8007. enumerable: true,
  8008. configurable: true
  8009. });
  8010. Object.defineProperty(Engine, "ALPHA_ADD", {
  8011. get: function () {
  8012. return Engine._ALPHA_ADD;
  8013. },
  8014. enumerable: true,
  8015. configurable: true
  8016. });
  8017. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8018. get: function () {
  8019. return Engine._ALPHA_COMBINE;
  8020. },
  8021. enumerable: true,
  8022. configurable: true
  8023. });
  8024. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8025. get: function () {
  8026. return Engine._ALPHA_SUBTRACT;
  8027. },
  8028. enumerable: true,
  8029. configurable: true
  8030. });
  8031. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8032. get: function () {
  8033. return Engine._ALPHA_MULTIPLY;
  8034. },
  8035. enumerable: true,
  8036. configurable: true
  8037. });
  8038. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8039. get: function () {
  8040. return Engine._ALPHA_MAXIMIZED;
  8041. },
  8042. enumerable: true,
  8043. configurable: true
  8044. });
  8045. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8046. get: function () {
  8047. return Engine._ALPHA_PREMULTIPLIED;
  8048. },
  8049. enumerable: true,
  8050. configurable: true
  8051. });
  8052. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8053. get: function () {
  8054. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8055. },
  8056. enumerable: true,
  8057. configurable: true
  8058. });
  8059. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8060. get: function () {
  8061. return Engine._ALPHA_INTERPOLATE;
  8062. },
  8063. enumerable: true,
  8064. configurable: true
  8065. });
  8066. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8067. get: function () {
  8068. return Engine._ALPHA_SCREENMODE;
  8069. },
  8070. enumerable: true,
  8071. configurable: true
  8072. });
  8073. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8074. get: function () {
  8075. return Engine._DELAYLOADSTATE_NONE;
  8076. },
  8077. enumerable: true,
  8078. configurable: true
  8079. });
  8080. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8081. get: function () {
  8082. return Engine._DELAYLOADSTATE_LOADED;
  8083. },
  8084. enumerable: true,
  8085. configurable: true
  8086. });
  8087. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8088. get: function () {
  8089. return Engine._DELAYLOADSTATE_LOADING;
  8090. },
  8091. enumerable: true,
  8092. configurable: true
  8093. });
  8094. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8095. get: function () {
  8096. return Engine._DELAYLOADSTATE_NOTLOADED;
  8097. },
  8098. enumerable: true,
  8099. configurable: true
  8100. });
  8101. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8102. get: function () {
  8103. return Engine._TEXTUREFORMAT_ALPHA;
  8104. },
  8105. enumerable: true,
  8106. configurable: true
  8107. });
  8108. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8109. get: function () {
  8110. return Engine._TEXTUREFORMAT_LUMINANCE;
  8111. },
  8112. enumerable: true,
  8113. configurable: true
  8114. });
  8115. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8116. get: function () {
  8117. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8118. },
  8119. enumerable: true,
  8120. configurable: true
  8121. });
  8122. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8123. get: function () {
  8124. return Engine._TEXTUREFORMAT_RGB;
  8125. },
  8126. enumerable: true,
  8127. configurable: true
  8128. });
  8129. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8130. get: function () {
  8131. return Engine._TEXTUREFORMAT_RGBA;
  8132. },
  8133. enumerable: true,
  8134. configurable: true
  8135. });
  8136. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8137. get: function () {
  8138. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8139. },
  8140. enumerable: true,
  8141. configurable: true
  8142. });
  8143. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8144. get: function () {
  8145. return Engine._TEXTURETYPE_FLOAT;
  8146. },
  8147. enumerable: true,
  8148. configurable: true
  8149. });
  8150. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8151. get: function () {
  8152. return Engine._TEXTURETYPE_HALF_FLOAT;
  8153. },
  8154. enumerable: true,
  8155. configurable: true
  8156. });
  8157. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8158. get: function () {
  8159. return Engine._SCALEMODE_FLOOR;
  8160. },
  8161. enumerable: true,
  8162. configurable: true
  8163. });
  8164. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8165. get: function () {
  8166. return Engine._SCALEMODE_NEAREST;
  8167. },
  8168. enumerable: true,
  8169. configurable: true
  8170. });
  8171. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8172. get: function () {
  8173. return Engine._SCALEMODE_CEILING;
  8174. },
  8175. enumerable: true,
  8176. configurable: true
  8177. });
  8178. Object.defineProperty(Engine, "Version", {
  8179. get: function () {
  8180. return "3.1-alpha";
  8181. },
  8182. enumerable: true,
  8183. configurable: true
  8184. });
  8185. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8186. get: function () {
  8187. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8188. },
  8189. enumerable: true,
  8190. configurable: true
  8191. });
  8192. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8193. get: function () {
  8194. return this._webGLVersion < 2 || this.forcePOTTextures;
  8195. },
  8196. enumerable: true,
  8197. configurable: true
  8198. });
  8199. Object.defineProperty(Engine.prototype, "badOS", {
  8200. get: function () {
  8201. return this._badOS;
  8202. },
  8203. enumerable: true,
  8204. configurable: true
  8205. });
  8206. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8207. get: function () {
  8208. return this._badDesktopOS;
  8209. },
  8210. enumerable: true,
  8211. configurable: true
  8212. });
  8213. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8214. get: function () {
  8215. return this._performanceMonitor;
  8216. },
  8217. enumerable: true,
  8218. configurable: true
  8219. });
  8220. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8221. get: function () {
  8222. return this._texturesSupported;
  8223. },
  8224. enumerable: true,
  8225. configurable: true
  8226. });
  8227. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8228. get: function () {
  8229. return this._textureFormatInUse;
  8230. },
  8231. enumerable: true,
  8232. configurable: true
  8233. });
  8234. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8235. // Empty texture
  8236. get: function () {
  8237. if (!this._emptyTexture) {
  8238. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8239. }
  8240. return this._emptyTexture;
  8241. },
  8242. enumerable: true,
  8243. configurable: true
  8244. });
  8245. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8246. get: function () {
  8247. if (!this._emptyCubeTexture) {
  8248. var faceData = new Uint8Array(4);
  8249. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8250. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8251. }
  8252. return this._emptyCubeTexture;
  8253. },
  8254. enumerable: true,
  8255. configurable: true
  8256. });
  8257. Engine.prototype._rebuildInternalTextures = function () {
  8258. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8259. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8260. var internalTexture = currentState_1[_i];
  8261. internalTexture._rebuild();
  8262. }
  8263. };
  8264. Engine.prototype._rebuildEffects = function () {
  8265. for (var key in this._compiledEffects) {
  8266. var effect = this._compiledEffects[key];
  8267. effect._prepareEffect();
  8268. }
  8269. BABYLON.Effect.ResetCache();
  8270. };
  8271. Engine.prototype._rebuildBuffers = function () {
  8272. // Index / Vertex
  8273. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8274. var scene = _a[_i];
  8275. scene.resetCachedMaterial();
  8276. scene._rebuildGeometries();
  8277. scene._rebuildTextures();
  8278. }
  8279. // Uniforms
  8280. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8281. var uniformBuffer = _c[_b];
  8282. uniformBuffer._rebuild();
  8283. }
  8284. };
  8285. Engine.prototype._initGLContext = function () {
  8286. // Caps
  8287. this._caps = new EngineCapabilities();
  8288. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8289. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8290. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8291. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8292. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8293. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8294. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8295. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8296. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8297. // Infos
  8298. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8299. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8300. if (rendererInfo != null) {
  8301. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8302. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8303. }
  8304. if (!this._glVendor) {
  8305. this._glVendor = "Unknown vendor";
  8306. }
  8307. if (!this._glRenderer) {
  8308. this._glRenderer = "Unknown renderer";
  8309. }
  8310. // Constants
  8311. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8312. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8313. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8314. this._gl.DEPTH24_STENCIL8 = 35056;
  8315. // Extensions
  8316. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8317. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8318. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8319. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8320. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8321. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8322. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8323. 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');
  8324. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8325. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8326. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8327. this._caps.highPrecisionShaderSupported = true;
  8328. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8329. // Checks if some of the format renders first to allow the use of webgl inspector.
  8330. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8331. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8332. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8333. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8334. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8335. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8336. if (this._webGLVersion > 1) {
  8337. this._gl.HALF_FLOAT_OES = 0x140B;
  8338. }
  8339. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8340. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8341. // Vertex array object
  8342. if (this._webGLVersion > 1) {
  8343. this._caps.vertexArrayObject = true;
  8344. }
  8345. else {
  8346. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8347. if (vertexArrayObjectExtension != null) {
  8348. this._caps.vertexArrayObject = true;
  8349. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8350. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8351. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8352. }
  8353. else {
  8354. this._caps.vertexArrayObject = false;
  8355. }
  8356. }
  8357. // Instances count
  8358. if (this._webGLVersion > 1) {
  8359. this._caps.instancedArrays = true;
  8360. }
  8361. else {
  8362. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8363. if (instanceExtension != null) {
  8364. this._caps.instancedArrays = true;
  8365. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8366. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8367. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8368. }
  8369. else {
  8370. this._caps.instancedArrays = false;
  8371. }
  8372. }
  8373. // Intelligently add supported compressed formats in order to check for.
  8374. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8375. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8376. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8377. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8378. if (this._caps.astc)
  8379. this.texturesSupported.push('-astc.ktx');
  8380. if (this._caps.s3tc)
  8381. this.texturesSupported.push('-dxt.ktx');
  8382. if (this._caps.pvrtc)
  8383. this.texturesSupported.push('-pvrtc.ktx');
  8384. if (this._caps.etc2)
  8385. this.texturesSupported.push('-etc2.ktx');
  8386. if (this._caps.etc1)
  8387. this.texturesSupported.push('-etc1.ktx');
  8388. if (this._gl.getShaderPrecisionFormat) {
  8389. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8390. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8391. }
  8392. // Depth buffer
  8393. this.setDepthBuffer(true);
  8394. this.setDepthFunctionToLessOrEqual();
  8395. this.setDepthWrite(true);
  8396. };
  8397. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8398. get: function () {
  8399. return this._webGLVersion;
  8400. },
  8401. enumerable: true,
  8402. configurable: true
  8403. });
  8404. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8405. /**
  8406. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8407. */
  8408. get: function () {
  8409. return this._isStencilEnable;
  8410. },
  8411. enumerable: true,
  8412. configurable: true
  8413. });
  8414. Engine.prototype._prepareWorkingCanvas = function () {
  8415. if (this._workingCanvas) {
  8416. return;
  8417. }
  8418. this._workingCanvas = document.createElement("canvas");
  8419. this._workingContext = this._workingCanvas.getContext("2d");
  8420. };
  8421. Engine.prototype.resetTextureCache = function () {
  8422. for (var key in this._activeTexturesCache) {
  8423. this._activeTexturesCache[key] = null;
  8424. }
  8425. };
  8426. Engine.prototype.isDeterministicLockStep = function () {
  8427. return this._deterministicLockstep;
  8428. };
  8429. Engine.prototype.getLockstepMaxSteps = function () {
  8430. return this._lockstepMaxSteps;
  8431. };
  8432. Engine.prototype.getGlInfo = function () {
  8433. return {
  8434. vendor: this._glVendor,
  8435. renderer: this._glRenderer,
  8436. version: this._glVersion
  8437. };
  8438. };
  8439. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8440. if (useScreen === void 0) { useScreen = false; }
  8441. var viewport = camera.viewport;
  8442. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8443. };
  8444. Engine.prototype.getRenderWidth = function (useScreen) {
  8445. if (useScreen === void 0) { useScreen = false; }
  8446. if (!useScreen && this._currentRenderTarget) {
  8447. return this._currentRenderTarget.width;
  8448. }
  8449. return this._gl.drawingBufferWidth;
  8450. };
  8451. Engine.prototype.getRenderHeight = function (useScreen) {
  8452. if (useScreen === void 0) { useScreen = false; }
  8453. if (!useScreen && this._currentRenderTarget) {
  8454. return this._currentRenderTarget.height;
  8455. }
  8456. return this._gl.drawingBufferHeight;
  8457. };
  8458. Engine.prototype.getRenderingCanvas = function () {
  8459. return this._renderingCanvas;
  8460. };
  8461. Engine.prototype.getRenderingCanvasClientRect = function () {
  8462. return this._renderingCanvas.getBoundingClientRect();
  8463. };
  8464. Engine.prototype.setHardwareScalingLevel = function (level) {
  8465. this._hardwareScalingLevel = level;
  8466. this.resize();
  8467. };
  8468. Engine.prototype.getHardwareScalingLevel = function () {
  8469. return this._hardwareScalingLevel;
  8470. };
  8471. Engine.prototype.getLoadedTexturesCache = function () {
  8472. return this._internalTexturesCache;
  8473. };
  8474. Engine.prototype.getCaps = function () {
  8475. return this._caps;
  8476. };
  8477. Object.defineProperty(Engine.prototype, "drawCalls", {
  8478. /** The number of draw calls submitted last frame */
  8479. get: function () {
  8480. return this._drawCalls.current;
  8481. },
  8482. enumerable: true,
  8483. configurable: true
  8484. });
  8485. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8486. get: function () {
  8487. return this._drawCalls;
  8488. },
  8489. enumerable: true,
  8490. configurable: true
  8491. });
  8492. Engine.prototype.getDepthFunction = function () {
  8493. return this._depthCullingState.depthFunc;
  8494. };
  8495. Engine.prototype.setDepthFunction = function (depthFunc) {
  8496. this._depthCullingState.depthFunc = depthFunc;
  8497. };
  8498. Engine.prototype.setDepthFunctionToGreater = function () {
  8499. this._depthCullingState.depthFunc = this._gl.GREATER;
  8500. };
  8501. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8502. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8503. };
  8504. Engine.prototype.setDepthFunctionToLess = function () {
  8505. this._depthCullingState.depthFunc = this._gl.LESS;
  8506. };
  8507. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8508. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8509. };
  8510. Engine.prototype.getStencilBuffer = function () {
  8511. return this._stencilState.stencilTest;
  8512. };
  8513. Engine.prototype.setStencilBuffer = function (enable) {
  8514. this._stencilState.stencilTest = enable;
  8515. };
  8516. Engine.prototype.getStencilMask = function () {
  8517. return this._stencilState.stencilMask;
  8518. };
  8519. Engine.prototype.setStencilMask = function (mask) {
  8520. this._stencilState.stencilMask = mask;
  8521. };
  8522. Engine.prototype.getStencilFunction = function () {
  8523. return this._stencilState.stencilFunc;
  8524. };
  8525. Engine.prototype.getStencilFunctionReference = function () {
  8526. return this._stencilState.stencilFuncRef;
  8527. };
  8528. Engine.prototype.getStencilFunctionMask = function () {
  8529. return this._stencilState.stencilFuncMask;
  8530. };
  8531. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8532. this._stencilState.stencilFunc = stencilFunc;
  8533. };
  8534. Engine.prototype.setStencilFunctionReference = function (reference) {
  8535. this._stencilState.stencilFuncRef = reference;
  8536. };
  8537. Engine.prototype.setStencilFunctionMask = function (mask) {
  8538. this._stencilState.stencilFuncMask = mask;
  8539. };
  8540. Engine.prototype.getStencilOperationFail = function () {
  8541. return this._stencilState.stencilOpStencilFail;
  8542. };
  8543. Engine.prototype.getStencilOperationDepthFail = function () {
  8544. return this._stencilState.stencilOpDepthFail;
  8545. };
  8546. Engine.prototype.getStencilOperationPass = function () {
  8547. return this._stencilState.stencilOpStencilDepthPass;
  8548. };
  8549. Engine.prototype.setStencilOperationFail = function (operation) {
  8550. this._stencilState.stencilOpStencilFail = operation;
  8551. };
  8552. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8553. this._stencilState.stencilOpDepthFail = operation;
  8554. };
  8555. Engine.prototype.setStencilOperationPass = function (operation) {
  8556. this._stencilState.stencilOpStencilDepthPass = operation;
  8557. };
  8558. Engine.prototype.setDitheringState = function (value) {
  8559. if (value) {
  8560. this._gl.enable(this._gl.DITHER);
  8561. }
  8562. else {
  8563. this._gl.disable(this._gl.DITHER);
  8564. }
  8565. };
  8566. /**
  8567. * stop executing a render loop function and remove it from the execution array
  8568. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8569. */
  8570. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8571. if (!renderFunction) {
  8572. this._activeRenderLoops = [];
  8573. return;
  8574. }
  8575. var index = this._activeRenderLoops.indexOf(renderFunction);
  8576. if (index >= 0) {
  8577. this._activeRenderLoops.splice(index, 1);
  8578. }
  8579. };
  8580. Engine.prototype._renderLoop = function () {
  8581. if (!this._contextWasLost) {
  8582. var shouldRender = true;
  8583. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8584. shouldRender = false;
  8585. }
  8586. if (shouldRender) {
  8587. // Start new frame
  8588. this.beginFrame();
  8589. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8590. var renderFunction = this._activeRenderLoops[index];
  8591. renderFunction();
  8592. }
  8593. // Present
  8594. this.endFrame();
  8595. }
  8596. }
  8597. if (this._activeRenderLoops.length > 0) {
  8598. // Register new frame
  8599. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8600. }
  8601. else {
  8602. this._renderingQueueLaunched = false;
  8603. }
  8604. };
  8605. /**
  8606. * Register and execute a render loop. The engine can have more than one render function.
  8607. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8608. * @example
  8609. * engine.runRenderLoop(function () {
  8610. * scene.render()
  8611. * })
  8612. */
  8613. Engine.prototype.runRenderLoop = function (renderFunction) {
  8614. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8615. return;
  8616. }
  8617. this._activeRenderLoops.push(renderFunction);
  8618. if (!this._renderingQueueLaunched) {
  8619. this._renderingQueueLaunched = true;
  8620. this._bindedRenderFunction = this._renderLoop.bind(this);
  8621. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8622. }
  8623. };
  8624. /**
  8625. * Toggle full screen mode.
  8626. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8627. * @param {any} options - an options object to be sent to the requestFullscreen function
  8628. */
  8629. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8630. if (this.isFullscreen) {
  8631. BABYLON.Tools.ExitFullscreen();
  8632. }
  8633. else {
  8634. this._pointerLockRequested = requestPointerLock;
  8635. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8636. }
  8637. };
  8638. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8639. if (stencil === void 0) { stencil = false; }
  8640. this.applyStates();
  8641. var mode = 0;
  8642. if (backBuffer && color) {
  8643. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8644. mode |= this._gl.COLOR_BUFFER_BIT;
  8645. }
  8646. if (depth) {
  8647. this._gl.clearDepth(1.0);
  8648. mode |= this._gl.DEPTH_BUFFER_BIT;
  8649. }
  8650. if (stencil) {
  8651. this._gl.clearStencil(0);
  8652. mode |= this._gl.STENCIL_BUFFER_BIT;
  8653. }
  8654. this._gl.clear(mode);
  8655. };
  8656. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8657. var gl = this._gl;
  8658. // Save state
  8659. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8660. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8661. // Change state
  8662. gl.enable(gl.SCISSOR_TEST);
  8663. gl.scissor(x, y, width, height);
  8664. // Clear
  8665. this.clear(clearColor, true, true, true);
  8666. // Restore state
  8667. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8668. if (curScissor === true) {
  8669. gl.enable(gl.SCISSOR_TEST);
  8670. }
  8671. else {
  8672. gl.disable(gl.SCISSOR_TEST);
  8673. }
  8674. };
  8675. /**
  8676. * Set the WebGL's viewport
  8677. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8678. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8679. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8680. */
  8681. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8682. var width = requiredWidth || this.getRenderWidth();
  8683. var height = requiredHeight || this.getRenderHeight();
  8684. var x = viewport.x || 0;
  8685. var y = viewport.y || 0;
  8686. this._cachedViewport = viewport;
  8687. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8688. };
  8689. /**
  8690. * Directly set the WebGL Viewport
  8691. * The x, y, width & height are directly passed to the WebGL call
  8692. * @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.
  8693. */
  8694. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8695. var currentViewport = this._cachedViewport;
  8696. this._cachedViewport = null;
  8697. this._gl.viewport(x, y, width, height);
  8698. return currentViewport;
  8699. };
  8700. Engine.prototype.beginFrame = function () {
  8701. this._measureFps();
  8702. };
  8703. Engine.prototype.endFrame = function () {
  8704. //force a flush in case we are using a bad OS.
  8705. if (this._badOS) {
  8706. this.flushFramebuffer();
  8707. }
  8708. //submit frame to the vr device, if enabled
  8709. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8710. this._vrDisplayEnabled.submitFrame();
  8711. }
  8712. };
  8713. /**
  8714. * resize the view according to the canvas' size.
  8715. * @example
  8716. * window.addEventListener("resize", function () {
  8717. * engine.resize();
  8718. * });
  8719. */
  8720. Engine.prototype.resize = function () {
  8721. // We're not resizing the size of the canvas while in VR mode & presenting
  8722. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8723. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8724. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8725. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8726. }
  8727. };
  8728. /**
  8729. * force a specific size of the canvas
  8730. * @param {number} width - the new canvas' width
  8731. * @param {number} height - the new canvas' height
  8732. */
  8733. Engine.prototype.setSize = function (width, height) {
  8734. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8735. return;
  8736. }
  8737. this._renderingCanvas.width = width;
  8738. this._renderingCanvas.height = height;
  8739. for (var index = 0; index < this.scenes.length; index++) {
  8740. var scene = this.scenes[index];
  8741. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8742. var cam = scene.cameras[camIndex];
  8743. cam._currentRenderId = 0;
  8744. }
  8745. }
  8746. if (this.onResizeObservable.hasObservers) {
  8747. this.onResizeObservable.notifyObservers(this);
  8748. }
  8749. };
  8750. //WebVR functions
  8751. Engine.prototype.isVRDevicePresent = function (callback) {
  8752. this.getVRDevice(null, function (device) {
  8753. callback(device !== null);
  8754. });
  8755. };
  8756. Engine.prototype.getVRDevice = function (name, callback) {
  8757. if (!this.vrDisplaysPromise) {
  8758. callback(null);
  8759. return;
  8760. }
  8761. this.vrDisplaysPromise.then(function (devices) {
  8762. if (devices.length > 0) {
  8763. if (name) {
  8764. var found = devices.some(function (device) {
  8765. if (device.displayName === name) {
  8766. callback(device);
  8767. return true;
  8768. }
  8769. else {
  8770. return false;
  8771. }
  8772. });
  8773. if (!found) {
  8774. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8775. callback(devices[0]);
  8776. }
  8777. }
  8778. else {
  8779. //choose the first one
  8780. callback(devices[0]);
  8781. }
  8782. }
  8783. else {
  8784. BABYLON.Tools.Error("No WebVR devices found!");
  8785. callback(null);
  8786. }
  8787. });
  8788. };
  8789. Engine.prototype.initWebVR = function () {
  8790. if (!this.vrDisplaysPromise) {
  8791. this._getVRDisplays();
  8792. }
  8793. };
  8794. Engine.prototype.enableVR = function (vrDevice) {
  8795. this._vrDisplayEnabled = vrDevice;
  8796. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8797. };
  8798. Engine.prototype.disableVR = function () {
  8799. if (this._vrDisplayEnabled) {
  8800. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8801. }
  8802. };
  8803. Engine.prototype._getVRDisplays = function () {
  8804. var _this = this;
  8805. var getWebVRDevices = function (devices) {
  8806. _this._vrDisplays = devices.filter(function (device) {
  8807. return device instanceof VRDisplay;
  8808. });
  8809. return _this._vrDisplays;
  8810. };
  8811. if (navigator.getVRDisplays) {
  8812. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8813. }
  8814. };
  8815. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8816. if (this._currentRenderTarget) {
  8817. this.unBindFramebuffer(this._currentRenderTarget);
  8818. }
  8819. this._currentRenderTarget = texture;
  8820. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8821. var gl = this._gl;
  8822. if (texture.isCube) {
  8823. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8824. }
  8825. if (this._cachedViewport && !forceFullscreenViewport) {
  8826. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8827. }
  8828. else {
  8829. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8830. }
  8831. this.wipeCaches();
  8832. };
  8833. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8834. if (this._currentFramebuffer !== framebuffer) {
  8835. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8836. this._currentFramebuffer = framebuffer;
  8837. }
  8838. };
  8839. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8840. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8841. this._currentRenderTarget = null;
  8842. // If MSAA, we need to bitblt back to main texture
  8843. var gl = this._gl;
  8844. if (texture._MSAAFramebuffer) {
  8845. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8846. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8847. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8848. }
  8849. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8850. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8851. gl.generateMipmap(gl.TEXTURE_2D);
  8852. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8853. }
  8854. if (onBeforeUnbind) {
  8855. if (texture._MSAAFramebuffer) {
  8856. // Bind the correct framebuffer
  8857. this.bindUnboundFramebuffer(texture._framebuffer);
  8858. }
  8859. onBeforeUnbind();
  8860. }
  8861. this.bindUnboundFramebuffer(null);
  8862. };
  8863. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8864. if (texture.generateMipMaps) {
  8865. var gl = this._gl;
  8866. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8867. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8868. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8869. }
  8870. };
  8871. Engine.prototype.flushFramebuffer = function () {
  8872. this._gl.flush();
  8873. };
  8874. Engine.prototype.restoreDefaultFramebuffer = function () {
  8875. if (this._currentRenderTarget) {
  8876. this.unBindFramebuffer(this._currentRenderTarget);
  8877. }
  8878. else {
  8879. this.bindUnboundFramebuffer(null);
  8880. }
  8881. if (this._cachedViewport) {
  8882. this.setViewport(this._cachedViewport);
  8883. }
  8884. this.wipeCaches();
  8885. };
  8886. // UBOs
  8887. Engine.prototype.createUniformBuffer = function (elements) {
  8888. var ubo = this._gl.createBuffer();
  8889. this.bindUniformBuffer(ubo);
  8890. if (elements instanceof Float32Array) {
  8891. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8892. }
  8893. else {
  8894. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8895. }
  8896. this.bindUniformBuffer(null);
  8897. ubo.references = 1;
  8898. return ubo;
  8899. };
  8900. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8901. var ubo = this._gl.createBuffer();
  8902. this.bindUniformBuffer(ubo);
  8903. if (elements instanceof Float32Array) {
  8904. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8905. }
  8906. else {
  8907. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8908. }
  8909. this.bindUniformBuffer(null);
  8910. ubo.references = 1;
  8911. return ubo;
  8912. };
  8913. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8914. this.bindUniformBuffer(uniformBuffer);
  8915. if (offset === undefined) {
  8916. offset = 0;
  8917. }
  8918. if (count === undefined) {
  8919. if (elements instanceof Float32Array) {
  8920. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8921. }
  8922. else {
  8923. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8924. }
  8925. }
  8926. else {
  8927. if (elements instanceof Float32Array) {
  8928. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8929. }
  8930. else {
  8931. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8932. }
  8933. }
  8934. this.bindUniformBuffer(null);
  8935. };
  8936. // VBOs
  8937. Engine.prototype._resetVertexBufferBinding = function () {
  8938. this.bindArrayBuffer(null);
  8939. this._cachedVertexBuffers = null;
  8940. };
  8941. Engine.prototype.createVertexBuffer = function (vertices) {
  8942. var vbo = this._gl.createBuffer();
  8943. this.bindArrayBuffer(vbo);
  8944. if (vertices instanceof Float32Array) {
  8945. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8946. }
  8947. else {
  8948. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8949. }
  8950. this._resetVertexBufferBinding();
  8951. vbo.references = 1;
  8952. return vbo;
  8953. };
  8954. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8955. var vbo = this._gl.createBuffer();
  8956. this.bindArrayBuffer(vbo);
  8957. if (vertices instanceof Float32Array) {
  8958. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8959. }
  8960. else {
  8961. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8962. }
  8963. this._resetVertexBufferBinding();
  8964. vbo.references = 1;
  8965. return vbo;
  8966. };
  8967. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8968. this.bindArrayBuffer(vertexBuffer);
  8969. if (offset === undefined) {
  8970. offset = 0;
  8971. }
  8972. if (count === undefined) {
  8973. if (vertices instanceof Float32Array) {
  8974. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8975. }
  8976. else {
  8977. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8978. }
  8979. }
  8980. else {
  8981. if (vertices instanceof Float32Array) {
  8982. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8983. }
  8984. else {
  8985. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8986. }
  8987. }
  8988. this._resetVertexBufferBinding();
  8989. };
  8990. Engine.prototype._resetIndexBufferBinding = function () {
  8991. this.bindIndexBuffer(null);
  8992. this._cachedIndexBuffer = null;
  8993. };
  8994. Engine.prototype.createIndexBuffer = function (indices) {
  8995. var vbo = this._gl.createBuffer();
  8996. this.bindIndexBuffer(vbo);
  8997. // Check for 32 bits indices
  8998. var arrayBuffer;
  8999. var need32Bits = false;
  9000. if (indices instanceof Uint16Array) {
  9001. arrayBuffer = indices;
  9002. }
  9003. else {
  9004. //check 32 bit support
  9005. if (this._caps.uintIndices) {
  9006. if (indices instanceof Uint32Array) {
  9007. arrayBuffer = indices;
  9008. need32Bits = true;
  9009. }
  9010. else {
  9011. //number[] or Int32Array, check if 32 bit is necessary
  9012. for (var index = 0; index < indices.length; index++) {
  9013. if (indices[index] > 65535) {
  9014. need32Bits = true;
  9015. break;
  9016. }
  9017. }
  9018. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9019. }
  9020. }
  9021. else {
  9022. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9023. arrayBuffer = new Uint16Array(indices);
  9024. }
  9025. }
  9026. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  9027. this._resetIndexBufferBinding();
  9028. vbo.references = 1;
  9029. vbo.is32Bits = need32Bits;
  9030. return vbo;
  9031. };
  9032. Engine.prototype.bindArrayBuffer = function (buffer) {
  9033. if (!this._vaoRecordInProgress) {
  9034. this._unbindVertexArrayObject();
  9035. }
  9036. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9037. };
  9038. Engine.prototype.bindUniformBuffer = function (buffer) {
  9039. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9040. };
  9041. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9042. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9043. };
  9044. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9045. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9046. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9047. };
  9048. ;
  9049. Engine.prototype.bindIndexBuffer = function (buffer) {
  9050. if (!this._vaoRecordInProgress) {
  9051. this._unbindVertexArrayObject();
  9052. }
  9053. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9054. };
  9055. Engine.prototype.bindBuffer = function (buffer, target) {
  9056. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9057. this._gl.bindBuffer(target, buffer);
  9058. this._currentBoundBuffer[target] = buffer;
  9059. }
  9060. };
  9061. Engine.prototype.updateArrayBuffer = function (data) {
  9062. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9063. };
  9064. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9065. var pointer = this._currentBufferPointers[indx];
  9066. var changed = false;
  9067. if (!pointer.active) {
  9068. changed = true;
  9069. pointer.active = true;
  9070. pointer.index = indx;
  9071. pointer.size = size;
  9072. pointer.type = type;
  9073. pointer.normalized = normalized;
  9074. pointer.stride = stride;
  9075. pointer.offset = offset;
  9076. pointer.buffer = buffer;
  9077. }
  9078. else {
  9079. if (pointer.buffer !== buffer) {
  9080. pointer.buffer = buffer;
  9081. changed = true;
  9082. }
  9083. if (pointer.size !== size) {
  9084. pointer.size = size;
  9085. changed = true;
  9086. }
  9087. if (pointer.type !== type) {
  9088. pointer.type = type;
  9089. changed = true;
  9090. }
  9091. if (pointer.normalized !== normalized) {
  9092. pointer.normalized = normalized;
  9093. changed = true;
  9094. }
  9095. if (pointer.stride !== stride) {
  9096. pointer.stride = stride;
  9097. changed = true;
  9098. }
  9099. if (pointer.offset !== offset) {
  9100. pointer.offset = offset;
  9101. changed = true;
  9102. }
  9103. }
  9104. if (changed || this._vaoRecordInProgress) {
  9105. this.bindArrayBuffer(buffer);
  9106. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9107. }
  9108. };
  9109. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9110. if (indexBuffer == null) {
  9111. return;
  9112. }
  9113. if (this._cachedIndexBuffer !== indexBuffer) {
  9114. this._cachedIndexBuffer = indexBuffer;
  9115. this.bindIndexBuffer(indexBuffer);
  9116. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9117. }
  9118. };
  9119. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9120. var attributes = effect.getAttributesNames();
  9121. if (!this._vaoRecordInProgress) {
  9122. this._unbindVertexArrayObject();
  9123. }
  9124. this.unbindAllAttributes();
  9125. for (var index = 0; index < attributes.length; index++) {
  9126. var order = effect.getAttributeLocation(index);
  9127. if (order >= 0) {
  9128. var vertexBuffer = vertexBuffers[attributes[index]];
  9129. if (!vertexBuffer) {
  9130. continue;
  9131. }
  9132. this._gl.enableVertexAttribArray(order);
  9133. if (!this._vaoRecordInProgress) {
  9134. this._vertexAttribArraysEnabled[order] = true;
  9135. }
  9136. var buffer = vertexBuffer.getBuffer();
  9137. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9138. if (vertexBuffer.getIsInstanced()) {
  9139. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9140. if (!this._vaoRecordInProgress) {
  9141. this._currentInstanceLocations.push(order);
  9142. this._currentInstanceBuffers.push(buffer);
  9143. }
  9144. }
  9145. }
  9146. }
  9147. };
  9148. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9149. var vao = this._gl.createVertexArray();
  9150. this._vaoRecordInProgress = true;
  9151. this._gl.bindVertexArray(vao);
  9152. this._mustWipeVertexAttributes = true;
  9153. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9154. this.bindIndexBuffer(indexBuffer);
  9155. this._vaoRecordInProgress = false;
  9156. this._gl.bindVertexArray(null);
  9157. return vao;
  9158. };
  9159. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9160. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9161. this._cachedVertexArrayObject = vertexArrayObject;
  9162. this._gl.bindVertexArray(vertexArrayObject);
  9163. this._cachedVertexBuffers = null;
  9164. this._cachedIndexBuffer = null;
  9165. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9166. this._mustWipeVertexAttributes = true;
  9167. }
  9168. };
  9169. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9170. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9171. this._cachedVertexBuffers = vertexBuffer;
  9172. this._cachedEffectForVertexBuffers = effect;
  9173. var attributesCount = effect.getAttributesCount();
  9174. this._unbindVertexArrayObject();
  9175. this.unbindAllAttributes();
  9176. var offset = 0;
  9177. for (var index = 0; index < attributesCount; index++) {
  9178. if (index < vertexDeclaration.length) {
  9179. var order = effect.getAttributeLocation(index);
  9180. if (order >= 0) {
  9181. this._gl.enableVertexAttribArray(order);
  9182. this._vertexAttribArraysEnabled[order] = true;
  9183. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9184. }
  9185. offset += vertexDeclaration[index] * 4;
  9186. }
  9187. }
  9188. }
  9189. this._bindIndexBufferWithCache(indexBuffer);
  9190. };
  9191. Engine.prototype._unbindVertexArrayObject = function () {
  9192. if (!this._cachedVertexArrayObject) {
  9193. return;
  9194. }
  9195. this._cachedVertexArrayObject = null;
  9196. this._gl.bindVertexArray(null);
  9197. };
  9198. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9199. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9200. this._cachedVertexBuffers = vertexBuffers;
  9201. this._cachedEffectForVertexBuffers = effect;
  9202. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9203. }
  9204. this._bindIndexBufferWithCache(indexBuffer);
  9205. };
  9206. Engine.prototype.unbindInstanceAttributes = function () {
  9207. var boundBuffer;
  9208. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9209. var instancesBuffer = this._currentInstanceBuffers[i];
  9210. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9211. boundBuffer = instancesBuffer;
  9212. this.bindArrayBuffer(instancesBuffer);
  9213. }
  9214. var offsetLocation = this._currentInstanceLocations[i];
  9215. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9216. }
  9217. this._currentInstanceBuffers.length = 0;
  9218. this._currentInstanceLocations.length = 0;
  9219. };
  9220. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9221. this._gl.deleteVertexArray(vao);
  9222. };
  9223. Engine.prototype._releaseBuffer = function (buffer) {
  9224. buffer.references--;
  9225. if (buffer.references === 0) {
  9226. this._gl.deleteBuffer(buffer);
  9227. return true;
  9228. }
  9229. return false;
  9230. };
  9231. Engine.prototype.createInstancesBuffer = function (capacity) {
  9232. var buffer = this._gl.createBuffer();
  9233. buffer.capacity = capacity;
  9234. this.bindArrayBuffer(buffer);
  9235. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9236. return buffer;
  9237. };
  9238. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9239. this._gl.deleteBuffer(buffer);
  9240. };
  9241. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9242. this.bindArrayBuffer(instancesBuffer);
  9243. if (data) {
  9244. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9245. }
  9246. if (offsetLocations[0].index !== undefined) {
  9247. var stride = 0;
  9248. for (var i = 0; i < offsetLocations.length; i++) {
  9249. var ai = offsetLocations[i];
  9250. stride += ai.attributeSize * 4;
  9251. }
  9252. for (var i = 0; i < offsetLocations.length; i++) {
  9253. var ai = offsetLocations[i];
  9254. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9255. this._gl.enableVertexAttribArray(ai.index);
  9256. this._vertexAttribArraysEnabled[ai.index] = true;
  9257. }
  9258. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9259. this._gl.vertexAttribDivisor(ai.index, 1);
  9260. this._currentInstanceLocations.push(ai.index);
  9261. this._currentInstanceBuffers.push(instancesBuffer);
  9262. }
  9263. }
  9264. else {
  9265. for (var index = 0; index < 4; index++) {
  9266. var offsetLocation = offsetLocations[index];
  9267. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9268. this._gl.enableVertexAttribArray(offsetLocation);
  9269. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9270. }
  9271. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9272. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9273. this._currentInstanceLocations.push(offsetLocation);
  9274. this._currentInstanceBuffers.push(instancesBuffer);
  9275. }
  9276. }
  9277. };
  9278. Engine.prototype.applyStates = function () {
  9279. this._depthCullingState.apply(this._gl);
  9280. this._stencilState.apply(this._gl);
  9281. this._alphaState.apply(this._gl);
  9282. };
  9283. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9284. // Apply states
  9285. this.applyStates();
  9286. this._drawCalls.addCount(1, false);
  9287. // Render
  9288. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9289. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9290. if (instancesCount) {
  9291. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9292. return;
  9293. }
  9294. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9295. };
  9296. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9297. // Apply states
  9298. this.applyStates();
  9299. this._drawCalls.addCount(1, false);
  9300. if (instancesCount) {
  9301. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9302. return;
  9303. }
  9304. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9305. };
  9306. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9307. // Apply states
  9308. this.applyStates();
  9309. this._drawCalls.addCount(1, false);
  9310. if (instancesCount) {
  9311. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9312. return;
  9313. }
  9314. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9315. };
  9316. // Shaders
  9317. Engine.prototype._releaseEffect = function (effect) {
  9318. if (this._compiledEffects[effect._key]) {
  9319. delete this._compiledEffects[effect._key];
  9320. if (effect.getProgram()) {
  9321. this._gl.deleteProgram(effect.getProgram());
  9322. }
  9323. }
  9324. };
  9325. /**
  9326. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9327. * @param samplers An array of string used to represent textures
  9328. */
  9329. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9330. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9331. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9332. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9333. if (this._compiledEffects[name]) {
  9334. var compiledEffect = this._compiledEffects[name];
  9335. if (onCompiled && compiledEffect.isReady()) {
  9336. onCompiled(compiledEffect);
  9337. }
  9338. return compiledEffect;
  9339. }
  9340. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9341. effect._key = name;
  9342. this._compiledEffects[name] = effect;
  9343. return effect;
  9344. };
  9345. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9346. if (uniformsNames === void 0) { uniformsNames = []; }
  9347. if (samplers === void 0) { samplers = []; }
  9348. if (defines === void 0) { defines = ""; }
  9349. return this.createEffect({
  9350. vertex: "particles",
  9351. fragmentElement: fragmentName
  9352. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9353. };
  9354. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9355. context = context || this._gl;
  9356. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9357. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9358. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9359. var shaderProgram = context.createProgram();
  9360. context.attachShader(shaderProgram, vertexShader);
  9361. context.attachShader(shaderProgram, fragmentShader);
  9362. context.linkProgram(shaderProgram);
  9363. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9364. if (!linked) {
  9365. context.validateProgram(shaderProgram);
  9366. var error = context.getProgramInfoLog(shaderProgram);
  9367. if (error) {
  9368. throw new Error(error);
  9369. }
  9370. }
  9371. context.deleteShader(vertexShader);
  9372. context.deleteShader(fragmentShader);
  9373. return shaderProgram;
  9374. };
  9375. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9376. var results = [];
  9377. for (var index = 0; index < uniformsNames.length; index++) {
  9378. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9379. }
  9380. return results;
  9381. };
  9382. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9383. var results = [];
  9384. for (var index = 0; index < attributesNames.length; index++) {
  9385. try {
  9386. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9387. }
  9388. catch (e) {
  9389. results.push(-1);
  9390. }
  9391. }
  9392. return results;
  9393. };
  9394. Engine.prototype.enableEffect = function (effect) {
  9395. // Use program
  9396. this.setProgram(effect.getProgram());
  9397. this._currentEffect = effect;
  9398. if (effect.onBind) {
  9399. effect.onBind(effect);
  9400. }
  9401. effect.onBindObservable.notifyObservers(effect);
  9402. };
  9403. Engine.prototype.setIntArray = function (uniform, array) {
  9404. if (!uniform)
  9405. return;
  9406. this._gl.uniform1iv(uniform, array);
  9407. };
  9408. Engine.prototype.setIntArray2 = function (uniform, array) {
  9409. if (!uniform || array.length % 2 !== 0)
  9410. return;
  9411. this._gl.uniform2iv(uniform, array);
  9412. };
  9413. Engine.prototype.setIntArray3 = function (uniform, array) {
  9414. if (!uniform || array.length % 3 !== 0)
  9415. return;
  9416. this._gl.uniform3iv(uniform, array);
  9417. };
  9418. Engine.prototype.setIntArray4 = function (uniform, array) {
  9419. if (!uniform || array.length % 4 !== 0)
  9420. return;
  9421. this._gl.uniform4iv(uniform, array);
  9422. };
  9423. Engine.prototype.setFloatArray = function (uniform, array) {
  9424. if (!uniform)
  9425. return;
  9426. this._gl.uniform1fv(uniform, array);
  9427. };
  9428. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9429. if (!uniform || array.length % 2 !== 0)
  9430. return;
  9431. this._gl.uniform2fv(uniform, array);
  9432. };
  9433. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9434. if (!uniform || array.length % 3 !== 0)
  9435. return;
  9436. this._gl.uniform3fv(uniform, array);
  9437. };
  9438. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9439. if (!uniform || array.length % 4 !== 0)
  9440. return;
  9441. this._gl.uniform4fv(uniform, array);
  9442. };
  9443. Engine.prototype.setArray = function (uniform, array) {
  9444. if (!uniform)
  9445. return;
  9446. this._gl.uniform1fv(uniform, array);
  9447. };
  9448. Engine.prototype.setArray2 = function (uniform, array) {
  9449. if (!uniform || array.length % 2 !== 0)
  9450. return;
  9451. this._gl.uniform2fv(uniform, array);
  9452. };
  9453. Engine.prototype.setArray3 = function (uniform, array) {
  9454. if (!uniform || array.length % 3 !== 0)
  9455. return;
  9456. this._gl.uniform3fv(uniform, array);
  9457. };
  9458. Engine.prototype.setArray4 = function (uniform, array) {
  9459. if (!uniform || array.length % 4 !== 0)
  9460. return;
  9461. this._gl.uniform4fv(uniform, array);
  9462. };
  9463. Engine.prototype.setMatrices = function (uniform, matrices) {
  9464. if (!uniform)
  9465. return;
  9466. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9467. };
  9468. Engine.prototype.setMatrix = function (uniform, matrix) {
  9469. if (!uniform)
  9470. return;
  9471. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9472. };
  9473. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9474. if (!uniform)
  9475. return;
  9476. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9477. };
  9478. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9479. if (!uniform)
  9480. return;
  9481. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9482. };
  9483. Engine.prototype.setFloat = function (uniform, value) {
  9484. if (!uniform)
  9485. return;
  9486. this._gl.uniform1f(uniform, value);
  9487. };
  9488. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9489. if (!uniform)
  9490. return;
  9491. this._gl.uniform2f(uniform, x, y);
  9492. };
  9493. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9494. if (!uniform)
  9495. return;
  9496. this._gl.uniform3f(uniform, x, y, z);
  9497. };
  9498. Engine.prototype.setBool = function (uniform, bool) {
  9499. if (!uniform)
  9500. return;
  9501. this._gl.uniform1i(uniform, bool);
  9502. };
  9503. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9504. if (!uniform)
  9505. return;
  9506. this._gl.uniform4f(uniform, x, y, z, w);
  9507. };
  9508. Engine.prototype.setColor3 = function (uniform, color3) {
  9509. if (!uniform)
  9510. return;
  9511. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9512. };
  9513. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9514. if (!uniform)
  9515. return;
  9516. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9517. };
  9518. // States
  9519. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9520. if (zOffset === void 0) { zOffset = 0; }
  9521. if (reverseSide === void 0) { reverseSide = false; }
  9522. // Culling
  9523. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9524. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9525. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9526. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9527. if (culling) {
  9528. this._depthCullingState.cullFace = cullFace;
  9529. this._depthCullingState.cull = true;
  9530. }
  9531. else {
  9532. this._depthCullingState.cull = false;
  9533. }
  9534. }
  9535. // Z offset
  9536. this.setZOffset(zOffset);
  9537. };
  9538. Engine.prototype.setZOffset = function (value) {
  9539. this._depthCullingState.zOffset = value;
  9540. };
  9541. Engine.prototype.getZOffset = function () {
  9542. return this._depthCullingState.zOffset;
  9543. };
  9544. Engine.prototype.setDepthBuffer = function (enable) {
  9545. this._depthCullingState.depthTest = enable;
  9546. };
  9547. Engine.prototype.getDepthWrite = function () {
  9548. return this._depthCullingState.depthMask;
  9549. };
  9550. Engine.prototype.setDepthWrite = function (enable) {
  9551. this._depthCullingState.depthMask = enable;
  9552. };
  9553. Engine.prototype.setColorWrite = function (enable) {
  9554. this._gl.colorMask(enable, enable, enable, enable);
  9555. };
  9556. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9557. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9558. };
  9559. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9560. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9561. if (this._alphaMode === mode) {
  9562. return;
  9563. }
  9564. switch (mode) {
  9565. case Engine.ALPHA_DISABLE:
  9566. this._alphaState.alphaBlend = false;
  9567. break;
  9568. case Engine.ALPHA_PREMULTIPLIED:
  9569. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9570. this._alphaState.alphaBlend = true;
  9571. break;
  9572. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9573. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9574. this._alphaState.alphaBlend = true;
  9575. break;
  9576. case Engine.ALPHA_COMBINE:
  9577. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9578. this._alphaState.alphaBlend = true;
  9579. break;
  9580. case Engine.ALPHA_ONEONE:
  9581. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9582. this._alphaState.alphaBlend = true;
  9583. break;
  9584. case Engine.ALPHA_ADD:
  9585. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9586. this._alphaState.alphaBlend = true;
  9587. break;
  9588. case Engine.ALPHA_SUBTRACT:
  9589. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9590. this._alphaState.alphaBlend = true;
  9591. break;
  9592. case Engine.ALPHA_MULTIPLY:
  9593. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9594. this._alphaState.alphaBlend = true;
  9595. break;
  9596. case Engine.ALPHA_MAXIMIZED:
  9597. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9598. this._alphaState.alphaBlend = true;
  9599. break;
  9600. case Engine.ALPHA_INTERPOLATE:
  9601. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9602. this._alphaState.alphaBlend = true;
  9603. break;
  9604. case Engine.ALPHA_SCREENMODE:
  9605. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9606. this._alphaState.alphaBlend = true;
  9607. break;
  9608. }
  9609. if (!noDepthWriteChange) {
  9610. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9611. }
  9612. this._alphaMode = mode;
  9613. };
  9614. Engine.prototype.getAlphaMode = function () {
  9615. return this._alphaMode;
  9616. };
  9617. Engine.prototype.setAlphaTesting = function (enable) {
  9618. this._alphaTest = enable;
  9619. };
  9620. Engine.prototype.getAlphaTesting = function () {
  9621. return !!this._alphaTest;
  9622. };
  9623. // Textures
  9624. Engine.prototype.wipeCaches = function (bruteForce) {
  9625. if (this.preventCacheWipeBetweenFrames) {
  9626. return;
  9627. }
  9628. this.resetTextureCache();
  9629. this._currentEffect = null;
  9630. // 6/8/2017: deltakosh: Should not be required anymore.
  9631. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9632. if (bruteForce) {
  9633. this._currentProgram = null;
  9634. this._stencilState.reset();
  9635. this._depthCullingState.reset();
  9636. this.setDepthFunctionToLessOrEqual();
  9637. this._alphaState.reset();
  9638. }
  9639. this._cachedVertexBuffers = null;
  9640. this._cachedIndexBuffer = null;
  9641. this._cachedEffectForVertexBuffers = null;
  9642. this._unbindVertexArrayObject();
  9643. this.bindIndexBuffer(null);
  9644. this.bindArrayBuffer(null);
  9645. };
  9646. /**
  9647. * Set the compressed texture format to use, based on the formats you have, and the formats
  9648. * supported by the hardware / browser.
  9649. *
  9650. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9651. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9652. * to API arguments needed to compressed textures. This puts the burden on the container
  9653. * generator to house the arcane code for determining these for current & future formats.
  9654. *
  9655. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9656. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9657. *
  9658. * Note: The result of this call is not taken into account when a texture is base64.
  9659. *
  9660. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9661. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9662. *
  9663. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9664. * @returns The extension selected.
  9665. */
  9666. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9667. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9668. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9669. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9670. return this._textureFormatInUse = this._texturesSupported[i];
  9671. }
  9672. }
  9673. }
  9674. // actively set format to nothing, to allow this to be called more than once
  9675. // and possibly fail the 2nd time
  9676. return this._textureFormatInUse = null;
  9677. };
  9678. Engine.prototype._createTexture = function () {
  9679. return this._gl.createTexture();
  9680. };
  9681. /**
  9682. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9683. * @param {string} urlArg- This contains one of the following:
  9684. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9685. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9686. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9687. *
  9688. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9689. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9690. * @param {Scene} scene- Needed for loading to the correct scene.
  9691. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9692. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9693. * @param {callback} onError- Optional callback to be called upon failure.
  9694. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9695. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9696. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9697. *
  9698. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9699. */
  9700. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9701. var _this = this;
  9702. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9703. if (onLoad === void 0) { onLoad = null; }
  9704. if (onError === void 0) { onError = null; }
  9705. if (buffer === void 0) { buffer = null; }
  9706. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9707. var fromData = url.substr(0, 5) === "data:";
  9708. var fromBlob = url.substr(0, 5) === "blob:";
  9709. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9710. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9711. // establish the file extension, if possible
  9712. var lastDot = url.lastIndexOf('.');
  9713. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9714. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9715. var isTGA = (extension === ".tga");
  9716. // determine if a ktx file should be substituted
  9717. var isKTX = false;
  9718. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9719. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9720. isKTX = true;
  9721. }
  9722. if (scene) {
  9723. scene._addPendingData(texture);
  9724. }
  9725. texture.url = url;
  9726. texture.generateMipMaps = !noMipmap;
  9727. texture.samplingMode = samplingMode;
  9728. texture.invertY = invertY;
  9729. if (!this._doNotHandleContextLost) {
  9730. // Keep a link to the buffer only if we plan to handle context lost
  9731. texture._buffer = buffer;
  9732. }
  9733. if (onLoad) {
  9734. texture.onLoadedObservable.add(onLoad);
  9735. }
  9736. if (!fallBack)
  9737. this._internalTexturesCache.push(texture);
  9738. var onerror = function () {
  9739. if (scene) {
  9740. scene._removePendingData(texture);
  9741. }
  9742. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9743. if (isKTX) {
  9744. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9745. }
  9746. else if (onError) {
  9747. onError();
  9748. }
  9749. };
  9750. var callback;
  9751. // processing for non-image formats
  9752. if (isKTX || isTGA || isDDS) {
  9753. if (isKTX) {
  9754. callback = function (data) {
  9755. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9756. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9757. ktx.uploadLevels(_this._gl, !noMipmap);
  9758. return false;
  9759. }, samplingMode);
  9760. };
  9761. }
  9762. else if (isTGA) {
  9763. callback = function (arrayBuffer) {
  9764. var data = new Uint8Array(arrayBuffer);
  9765. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9766. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9767. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9768. return false;
  9769. }, samplingMode);
  9770. };
  9771. }
  9772. else if (isDDS) {
  9773. callback = function (data) {
  9774. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9775. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9776. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9777. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9778. return false;
  9779. }, samplingMode);
  9780. };
  9781. }
  9782. if (!buffer) {
  9783. BABYLON.Tools.LoadFile(url, function (data) {
  9784. callback(data);
  9785. }, null, scene ? scene.database : null, true, onerror);
  9786. }
  9787. else {
  9788. callback(buffer);
  9789. }
  9790. // image format processing
  9791. }
  9792. else {
  9793. var onload = function (img) {
  9794. if (fromBlob && !_this._doNotHandleContextLost) {
  9795. // We need to store the image if we need to rebuild the texture
  9796. // in case of a webgl context lost
  9797. texture._buffer = img;
  9798. }
  9799. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9800. var gl = _this._gl;
  9801. var isPot = (img.width === potWidth && img.height === potHeight);
  9802. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9803. if (isPot) {
  9804. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9805. return false;
  9806. }
  9807. // Using shaders to rescale because canvas.drawImage is lossy
  9808. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9809. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9810. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9811. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9812. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9813. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9814. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9815. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9816. _this._releaseTexture(source);
  9817. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9818. continuationCallback();
  9819. });
  9820. return true;
  9821. }, samplingMode);
  9822. };
  9823. if (!fromData || isBase64)
  9824. if (buffer instanceof HTMLImageElement) {
  9825. onload(buffer);
  9826. }
  9827. else {
  9828. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9829. }
  9830. else if (buffer instanceof Array || typeof buffer === "string")
  9831. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9832. else
  9833. onload(buffer);
  9834. }
  9835. return texture;
  9836. };
  9837. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9838. var _this = this;
  9839. var rtt = this.createRenderTargetTexture({
  9840. width: destination.width,
  9841. height: destination.height,
  9842. }, {
  9843. generateMipMaps: false,
  9844. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9845. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9846. generateDepthBuffer: false,
  9847. generateStencilBuffer: false
  9848. });
  9849. if (!this._rescalePostProcess) {
  9850. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9851. }
  9852. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9853. _this._rescalePostProcess.onApply = function (effect) {
  9854. effect._bindTexture("textureSampler", source);
  9855. };
  9856. var hostingScene = scene;
  9857. if (!hostingScene) {
  9858. hostingScene = _this.scenes[_this.scenes.length - 1];
  9859. }
  9860. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9861. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9862. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9863. _this.unBindFramebuffer(rtt);
  9864. _this._releaseTexture(rtt);
  9865. if (onComplete) {
  9866. onComplete();
  9867. }
  9868. });
  9869. };
  9870. Engine.prototype._getInternalFormat = function (format) {
  9871. var internalFormat = this._gl.RGBA;
  9872. switch (format) {
  9873. case Engine.TEXTUREFORMAT_ALPHA:
  9874. internalFormat = this._gl.ALPHA;
  9875. break;
  9876. case Engine.TEXTUREFORMAT_LUMINANCE:
  9877. internalFormat = this._gl.LUMINANCE;
  9878. break;
  9879. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9880. internalFormat = this._gl.LUMINANCE_ALPHA;
  9881. break;
  9882. case Engine.TEXTUREFORMAT_RGB:
  9883. internalFormat = this._gl.RGB;
  9884. break;
  9885. case Engine.TEXTUREFORMAT_RGBA:
  9886. internalFormat = this._gl.RGBA;
  9887. break;
  9888. }
  9889. return internalFormat;
  9890. };
  9891. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9892. if (compression === void 0) { compression = null; }
  9893. var internalFormat = this._getInternalFormat(format);
  9894. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9895. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9896. if (!this._doNotHandleContextLost) {
  9897. texture._bufferView = data;
  9898. texture.format = format;
  9899. texture.invertY = invertY;
  9900. texture._compression = compression;
  9901. }
  9902. if (texture.width % 4 !== 0) {
  9903. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9904. }
  9905. if (compression) {
  9906. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  9907. }
  9908. else {
  9909. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9910. }
  9911. if (texture.generateMipMaps) {
  9912. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9913. }
  9914. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9915. this.resetTextureCache();
  9916. texture.isReady = true;
  9917. };
  9918. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9919. if (compression === void 0) { compression = null; }
  9920. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  9921. texture.baseWidth = width;
  9922. texture.baseHeight = height;
  9923. texture.width = width;
  9924. texture.height = height;
  9925. texture.format = format;
  9926. texture.generateMipMaps = generateMipMaps;
  9927. texture.samplingMode = samplingMode;
  9928. texture.invertY = invertY;
  9929. texture._compression = compression;
  9930. if (!this._doNotHandleContextLost) {
  9931. texture._bufferView = data;
  9932. }
  9933. this.updateRawTexture(texture, data, format, invertY, compression);
  9934. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9935. // Filters
  9936. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9937. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9938. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9939. if (generateMipMaps) {
  9940. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9941. }
  9942. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9943. this._internalTexturesCache.push(texture);
  9944. return texture;
  9945. };
  9946. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9947. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  9948. texture.baseWidth = width;
  9949. texture.baseHeight = height;
  9950. if (generateMipMaps) {
  9951. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9952. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9953. }
  9954. this.resetTextureCache();
  9955. texture.width = width;
  9956. texture.height = height;
  9957. texture.isReady = false;
  9958. texture.generateMipMaps = generateMipMaps;
  9959. texture.samplingMode = samplingMode;
  9960. this.updateTextureSamplingMode(samplingMode, texture);
  9961. this._internalTexturesCache.push(texture);
  9962. return texture;
  9963. };
  9964. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9965. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9966. if (texture.isCube) {
  9967. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9968. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9969. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9970. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9971. }
  9972. else {
  9973. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9974. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9975. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9976. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9977. }
  9978. texture.samplingMode = samplingMode;
  9979. };
  9980. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9981. if (premulAlpha === void 0) { premulAlpha = false; }
  9982. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9983. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9984. if (premulAlpha) {
  9985. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9986. }
  9987. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9988. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9989. if (texture.generateMipMaps) {
  9990. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9991. }
  9992. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9993. if (premulAlpha) {
  9994. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9995. }
  9996. this.resetTextureCache();
  9997. texture.isReady = true;
  9998. };
  9999. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10000. if (texture._isDisabled) {
  10001. return;
  10002. }
  10003. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10004. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10005. try {
  10006. // Testing video texture support
  10007. if (this._videoTextureSupported === undefined) {
  10008. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10009. if (this._gl.getError() !== 0) {
  10010. this._videoTextureSupported = false;
  10011. }
  10012. else {
  10013. this._videoTextureSupported = true;
  10014. }
  10015. }
  10016. // Copy video through the current working canvas if video texture is not supported
  10017. if (!this._videoTextureSupported) {
  10018. if (!texture._workingCanvas) {
  10019. texture._workingCanvas = document.createElement("canvas");
  10020. texture._workingContext = texture._workingCanvas.getContext("2d");
  10021. texture._workingCanvas.width = texture.width;
  10022. texture._workingCanvas.height = texture.height;
  10023. }
  10024. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10025. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10026. }
  10027. else {
  10028. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10029. }
  10030. if (texture.generateMipMaps) {
  10031. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10032. }
  10033. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10034. this.resetTextureCache();
  10035. texture.isReady = true;
  10036. }
  10037. catch (ex) {
  10038. // Something unexpected
  10039. // Let's disable the texture
  10040. texture._isDisabled = true;
  10041. }
  10042. };
  10043. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10044. var fullOptions = new RenderTargetCreationOptions();
  10045. if (options !== undefined && typeof options === "object") {
  10046. fullOptions.generateMipMaps = options.generateMipMaps;
  10047. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10048. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10049. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10050. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10051. }
  10052. else {
  10053. fullOptions.generateMipMaps = options;
  10054. fullOptions.generateDepthBuffer = true;
  10055. fullOptions.generateStencilBuffer = false;
  10056. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10057. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10058. }
  10059. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10060. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10061. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10062. }
  10063. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10064. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10065. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10066. }
  10067. var gl = this._gl;
  10068. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10069. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10070. var width = size.width || size;
  10071. var height = size.height || size;
  10072. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  10073. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10074. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10075. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10076. }
  10077. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10078. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10079. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10080. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10081. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10082. // Create the framebuffer
  10083. var framebuffer = gl.createFramebuffer();
  10084. this.bindUnboundFramebuffer(framebuffer);
  10085. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10086. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  10087. if (fullOptions.generateMipMaps) {
  10088. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10089. }
  10090. // Unbind
  10091. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10092. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10093. this.bindUnboundFramebuffer(null);
  10094. texture._framebuffer = framebuffer;
  10095. texture.baseWidth = width;
  10096. texture.baseHeight = height;
  10097. texture.width = width;
  10098. texture.height = height;
  10099. texture.isReady = true;
  10100. texture.samples = 1;
  10101. texture.generateMipMaps = fullOptions.generateMipMaps;
  10102. texture.samplingMode = fullOptions.samplingMode;
  10103. texture.type = fullOptions.type;
  10104. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10105. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  10106. this.resetTextureCache();
  10107. this._internalTexturesCache.push(texture);
  10108. return texture;
  10109. };
  10110. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10111. var generateMipMaps = false;
  10112. var generateDepthBuffer = true;
  10113. var generateStencilBuffer = false;
  10114. var generateDepthTexture = false;
  10115. var textureCount = 1;
  10116. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10117. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10118. var types = [], samplingModes = [];
  10119. if (options !== undefined) {
  10120. generateMipMaps = options.generateMipMaps;
  10121. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10122. generateStencilBuffer = options.generateStencilBuffer;
  10123. generateDepthTexture = options.generateDepthTexture;
  10124. textureCount = options.textureCount || 1;
  10125. if (options.types) {
  10126. types = options.types;
  10127. }
  10128. if (options.samplingModes) {
  10129. samplingModes = options.samplingModes;
  10130. }
  10131. }
  10132. var gl = this._gl;
  10133. // Create the framebuffer
  10134. var framebuffer = gl.createFramebuffer();
  10135. this.bindUnboundFramebuffer(framebuffer);
  10136. var width = size.width || size;
  10137. var height = size.height || size;
  10138. var textures = [];
  10139. var attachments = [];
  10140. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10141. for (var i = 0; i < textureCount; i++) {
  10142. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10143. var type = types[i] || defaultType;
  10144. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10145. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10146. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10147. }
  10148. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10149. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10150. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10151. }
  10152. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10153. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10154. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10155. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10156. }
  10157. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10158. var attachment = gl["COLOR_ATTACHMENT" + i];
  10159. textures.push(texture);
  10160. attachments.push(attachment);
  10161. gl.activeTexture(gl["TEXTURE" + i]);
  10162. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10163. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10164. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10165. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10166. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10167. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10168. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10169. if (generateMipMaps) {
  10170. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10171. }
  10172. // Unbind
  10173. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10174. texture._framebuffer = framebuffer;
  10175. texture._depthStencilBuffer = depthStencilBuffer;
  10176. texture.baseWidth = width;
  10177. texture.baseHeight = height;
  10178. texture.width = width;
  10179. texture.height = height;
  10180. texture.isReady = true;
  10181. texture.samples = 1;
  10182. texture.generateMipMaps = generateMipMaps;
  10183. texture.samplingMode = samplingMode;
  10184. texture.type = type;
  10185. texture._generateDepthBuffer = generateDepthBuffer;
  10186. texture._generateStencilBuffer = generateStencilBuffer;
  10187. this._internalTexturesCache.push(texture);
  10188. }
  10189. if (generateDepthTexture) {
  10190. // Depth texture
  10191. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10192. gl.activeTexture(gl.TEXTURE0);
  10193. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10194. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10195. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10196. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10197. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10198. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  10199. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10200. depthTexture._framebuffer = framebuffer;
  10201. depthTexture.baseWidth = width;
  10202. depthTexture.baseHeight = height;
  10203. depthTexture.width = width;
  10204. depthTexture.height = height;
  10205. depthTexture.isReady = true;
  10206. depthTexture.samples = 1;
  10207. depthTexture.generateMipMaps = generateMipMaps;
  10208. depthTexture.samplingMode = gl.NEAREST;
  10209. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10210. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10211. textures.push(depthTexture);
  10212. this._internalTexturesCache.push(depthTexture);
  10213. }
  10214. gl.drawBuffers(attachments);
  10215. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10216. this.bindUnboundFramebuffer(null);
  10217. this.resetTextureCache();
  10218. return textures;
  10219. };
  10220. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10221. if (samples === void 0) { samples = 1; }
  10222. var depthStencilBuffer = null;
  10223. var gl = this._gl;
  10224. // Create the depth/stencil buffer
  10225. if (generateStencilBuffer) {
  10226. depthStencilBuffer = gl.createRenderbuffer();
  10227. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10228. if (samples > 1) {
  10229. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10230. }
  10231. else {
  10232. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10233. }
  10234. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10235. }
  10236. else if (generateDepthBuffer) {
  10237. depthStencilBuffer = gl.createRenderbuffer();
  10238. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10239. if (samples > 1) {
  10240. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10241. }
  10242. else {
  10243. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10244. }
  10245. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10246. }
  10247. return depthStencilBuffer;
  10248. };
  10249. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10250. if (this.webGLVersion < 2) {
  10251. return 1;
  10252. }
  10253. if (texture.samples === samples) {
  10254. return samples;
  10255. }
  10256. var gl = this._gl;
  10257. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10258. // Dispose previous render buffers
  10259. if (texture._depthStencilBuffer) {
  10260. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10261. }
  10262. if (texture._MSAAFramebuffer) {
  10263. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10264. }
  10265. if (texture._MSAARenderBuffer) {
  10266. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10267. }
  10268. if (samples > 1) {
  10269. texture._MSAAFramebuffer = gl.createFramebuffer();
  10270. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10271. var colorRenderbuffer = gl.createRenderbuffer();
  10272. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10273. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10274. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10275. texture._MSAARenderBuffer = colorRenderbuffer;
  10276. }
  10277. else {
  10278. this.bindUnboundFramebuffer(texture._framebuffer);
  10279. }
  10280. texture.samples = samples;
  10281. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10282. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10283. this.bindUnboundFramebuffer(null);
  10284. return samples;
  10285. };
  10286. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10287. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10288. };
  10289. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10290. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10291. };
  10292. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10293. var gl = this._gl;
  10294. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10295. var generateMipMaps = true;
  10296. var generateDepthBuffer = true;
  10297. var generateStencilBuffer = false;
  10298. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10299. if (options !== undefined) {
  10300. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10301. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10302. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10303. if (options.samplingMode !== undefined) {
  10304. samplingMode = options.samplingMode;
  10305. }
  10306. }
  10307. texture.isCube = true;
  10308. texture.generateMipMaps = generateMipMaps;
  10309. texture.samples = 1;
  10310. texture.samplingMode = samplingMode;
  10311. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10312. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10313. for (var face = 0; face < 6; face++) {
  10314. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10315. }
  10316. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10317. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10318. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10319. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10320. // Create the framebuffer
  10321. var framebuffer = gl.createFramebuffer();
  10322. this.bindUnboundFramebuffer(framebuffer);
  10323. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10324. // Mipmaps
  10325. if (texture.generateMipMaps) {
  10326. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10327. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10328. }
  10329. // Unbind
  10330. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10331. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10332. this.bindUnboundFramebuffer(null);
  10333. texture._framebuffer = framebuffer;
  10334. texture.width = size;
  10335. texture.height = size;
  10336. texture.isReady = true;
  10337. this.resetTextureCache();
  10338. this._internalTexturesCache.push(texture);
  10339. return texture;
  10340. };
  10341. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10342. var _this = this;
  10343. if (onError === void 0) { onError = null; }
  10344. if (forcedExtension === void 0) { forcedExtension = null; }
  10345. var callback = function (loadData) {
  10346. if (!loadData) {
  10347. if (onLoad) {
  10348. onLoad(null);
  10349. }
  10350. return;
  10351. }
  10352. var texture = loadData.texture;
  10353. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10354. texture._lodGenerationScale = scale;
  10355. texture._lodGenerationOffset = offset;
  10356. if (_this._caps.textureLOD) {
  10357. // Do not add extra process if texture lod is supported.
  10358. if (onLoad) {
  10359. onLoad(texture);
  10360. }
  10361. return;
  10362. }
  10363. var mipSlices = 3;
  10364. var gl = _this._gl;
  10365. var width = loadData.width;
  10366. if (!width) {
  10367. return;
  10368. }
  10369. var textures = [];
  10370. for (var i = 0; i < mipSlices; i++) {
  10371. //compute LOD from even spacing in smoothness (matching shader calculation)
  10372. var smoothness = i / (mipSlices - 1);
  10373. var roughness = 1 - smoothness;
  10374. var minLODIndex = offset; // roughness = 0
  10375. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10376. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10377. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10378. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10379. glTextureFromLod.isCube = true;
  10380. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10381. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10382. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10383. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10384. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10385. if (loadData.isDDS) {
  10386. var info = loadData.info;
  10387. var data = loadData.data;
  10388. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10389. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10390. }
  10391. else {
  10392. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10393. }
  10394. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10395. // Wrap in a base texture for easy binding.
  10396. var lodTexture = new BABYLON.BaseTexture(scene);
  10397. lodTexture.isCube = true;
  10398. lodTexture._texture = glTextureFromLod;
  10399. glTextureFromLod.isReady = true;
  10400. textures.push(lodTexture);
  10401. }
  10402. texture._lodTextureHigh = textures[2];
  10403. texture._lodTextureMid = textures[1];
  10404. texture._lodTextureLow = textures[0];
  10405. if (onLoad) {
  10406. onLoad(texture);
  10407. }
  10408. };
  10409. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10410. };
  10411. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10412. var _this = this;
  10413. if (onLoad === void 0) { onLoad = null; }
  10414. if (onError === void 0) { onError = null; }
  10415. if (forcedExtension === void 0) { forcedExtension = null; }
  10416. var gl = this._gl;
  10417. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10418. texture.isCube = true;
  10419. texture.url = rootUrl;
  10420. texture.generateMipMaps = !noMipmap;
  10421. if (!this._doNotHandleContextLost) {
  10422. texture._extension = forcedExtension;
  10423. texture._files = files;
  10424. }
  10425. var isKTX = false;
  10426. var isDDS = false;
  10427. var lastDot = rootUrl.lastIndexOf('.');
  10428. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10429. if (this._textureFormatInUse) {
  10430. extension = this._textureFormatInUse;
  10431. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10432. isKTX = true;
  10433. }
  10434. else {
  10435. isDDS = (extension === ".dds");
  10436. }
  10437. if (isKTX) {
  10438. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10439. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10440. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10441. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10442. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10443. ktx.uploadLevels(_this._gl, !noMipmap);
  10444. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10445. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10446. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10447. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10448. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10449. _this.resetTextureCache();
  10450. texture.width = ktx.pixelWidth;
  10451. texture.height = ktx.pixelHeight;
  10452. texture.isReady = true;
  10453. }, null, null, true, onError);
  10454. }
  10455. else if (isDDS) {
  10456. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10457. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10458. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10459. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10460. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10461. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10462. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10463. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10464. }
  10465. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10466. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10467. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10468. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10469. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10470. _this.resetTextureCache();
  10471. texture.width = info.width;
  10472. texture.height = info.height;
  10473. texture.isReady = true;
  10474. texture.type = info.textureType;
  10475. if (onLoad) {
  10476. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10477. }
  10478. }, null, null, true, onError);
  10479. }
  10480. else {
  10481. cascadeLoad(rootUrl, scene, function (imgs) {
  10482. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10483. var height = width;
  10484. _this._prepareWorkingCanvas();
  10485. _this._workingCanvas.width = width;
  10486. _this._workingCanvas.height = height;
  10487. var faces = [
  10488. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10489. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10490. ];
  10491. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10492. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10493. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10494. for (var index = 0; index < faces.length; index++) {
  10495. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10496. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10497. }
  10498. if (!noMipmap) {
  10499. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10500. }
  10501. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10502. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10503. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10504. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10505. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10506. _this.resetTextureCache();
  10507. texture.width = width;
  10508. texture.height = height;
  10509. texture.isReady = true;
  10510. texture.format = format;
  10511. texture.onLoadedObservable.notifyObservers(texture);
  10512. texture.onLoadedObservable.clear();
  10513. if (onLoad) {
  10514. onLoad();
  10515. }
  10516. }, files, onError);
  10517. }
  10518. this._internalTexturesCache.push(texture);
  10519. return texture;
  10520. };
  10521. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10522. if (compression === void 0) { compression = null; }
  10523. if (level === void 0) { level = 0; }
  10524. texture._bufferViewArray = data;
  10525. texture.format = format;
  10526. texture.type = type;
  10527. texture.invertY = invertY;
  10528. texture._compression = compression;
  10529. var gl = this._gl;
  10530. var textureType = this._getWebGLTextureType(type);
  10531. var internalFormat = this._getInternalFormat(format);
  10532. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10533. var needConversion = false;
  10534. if (internalFormat === gl.RGB) {
  10535. internalFormat = gl.RGBA;
  10536. needConversion = true;
  10537. }
  10538. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10539. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10540. if (texture.width % 4 !== 0) {
  10541. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10542. }
  10543. // Data are known to be in +X +Y +Z -X -Y -Z
  10544. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10545. var faceData = data[faceIndex];
  10546. if (compression) {
  10547. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10548. }
  10549. else {
  10550. if (needConversion) {
  10551. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10552. }
  10553. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10554. }
  10555. }
  10556. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10557. if (isPot && texture.generateMipMaps && level === 0) {
  10558. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10559. }
  10560. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10561. this.resetTextureCache();
  10562. texture.isReady = true;
  10563. };
  10564. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10565. if (compression === void 0) { compression = null; }
  10566. var gl = this._gl;
  10567. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10568. texture.isCube = true;
  10569. texture.generateMipMaps = generateMipMaps;
  10570. texture.format = format;
  10571. texture.type = type;
  10572. if (!this._doNotHandleContextLost) {
  10573. texture._bufferViewArray = data;
  10574. }
  10575. var textureType = this._getWebGLTextureType(type);
  10576. var internalFormat = this._getInternalFormat(format);
  10577. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10578. var needConversion = false;
  10579. if (internalFormat === gl.RGB) {
  10580. internalFormat = gl.RGBA;
  10581. needConversion = true;
  10582. }
  10583. var width = size;
  10584. var height = width;
  10585. texture.width = width;
  10586. texture.height = height;
  10587. // Double check on POT to generate Mips.
  10588. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10589. if (!isPot) {
  10590. generateMipMaps = false;
  10591. }
  10592. // Upload data if needed. The texture won't be ready until then.
  10593. if (data) {
  10594. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10595. }
  10596. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10597. // Filters
  10598. if (data && generateMipMaps) {
  10599. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10600. }
  10601. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10604. }
  10605. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10606. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10607. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10608. }
  10609. else {
  10610. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10611. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10612. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10613. }
  10614. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10615. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10616. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10617. return texture;
  10618. };
  10619. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10620. var _this = this;
  10621. if (onLoad === void 0) { onLoad = null; }
  10622. if (onError === void 0) { onError = null; }
  10623. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10624. if (invertY === void 0) { invertY = false; }
  10625. var gl = this._gl;
  10626. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10627. scene._addPendingData(texture);
  10628. texture.url = url;
  10629. this._internalTexturesCache.push(texture);
  10630. var onerror = function () {
  10631. scene._removePendingData(texture);
  10632. if (onError) {
  10633. onError();
  10634. }
  10635. };
  10636. var internalCallback = function (data) {
  10637. var width = texture.width;
  10638. var height = texture.height;
  10639. var faceDataArrays = callback(data);
  10640. if (mipmmapGenerator) {
  10641. var textureType = _this._getWebGLTextureType(type);
  10642. var internalFormat = _this._getInternalFormat(format);
  10643. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10644. var needConversion = false;
  10645. if (internalFormat === gl.RGB) {
  10646. internalFormat = gl.RGBA;
  10647. needConversion = true;
  10648. }
  10649. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10650. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10651. var mipData = mipmmapGenerator(faceDataArrays);
  10652. for (var level = 0; level < mipData.length; level++) {
  10653. var mipSize = width >> level;
  10654. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10655. var mipFaceData = mipData[level][faceIndex];
  10656. if (needConversion) {
  10657. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10658. }
  10659. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10660. }
  10661. }
  10662. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10663. }
  10664. else {
  10665. texture.generateMipMaps = !noMipmap;
  10666. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10667. }
  10668. texture.isReady = true;
  10669. _this.resetTextureCache();
  10670. scene._removePendingData(texture);
  10671. if (onLoad) {
  10672. onLoad();
  10673. }
  10674. };
  10675. BABYLON.Tools.LoadFile(url, function (data) {
  10676. internalCallback(data);
  10677. }, onerror, scene.database, true);
  10678. return texture;
  10679. };
  10680. ;
  10681. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10682. var gl = this._gl;
  10683. if (!gl) {
  10684. return;
  10685. }
  10686. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10687. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10688. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10689. if (!noMipmap && !isCompressed) {
  10690. gl.generateMipmap(gl.TEXTURE_2D);
  10691. }
  10692. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10693. this.resetTextureCache();
  10694. if (scene) {
  10695. scene._removePendingData(texture);
  10696. }
  10697. texture.onLoadedObservable.notifyObservers(texture);
  10698. texture.onLoadedObservable.clear();
  10699. };
  10700. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10701. var _this = this;
  10702. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10703. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10704. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10705. var gl = this._gl;
  10706. if (!gl) {
  10707. return;
  10708. }
  10709. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10710. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10711. texture.baseWidth = width;
  10712. texture.baseHeight = height;
  10713. texture.width = potWidth;
  10714. texture.height = potHeight;
  10715. texture.isReady = true;
  10716. if (processFunction(potWidth, potHeight, function () {
  10717. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10718. })) {
  10719. // Returning as texture needs extra async steps
  10720. return;
  10721. }
  10722. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10723. };
  10724. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10725. // Create new RGBA data container.
  10726. var rgbaData;
  10727. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10728. rgbaData = new Float32Array(width * height * 4);
  10729. }
  10730. else {
  10731. rgbaData = new Uint32Array(width * height * 4);
  10732. }
  10733. // Convert each pixel.
  10734. for (var x = 0; x < width; x++) {
  10735. for (var y = 0; y < height; y++) {
  10736. var index = (y * width + x) * 3;
  10737. var newIndex = (y * width + x) * 4;
  10738. // Map Old Value to new value.
  10739. rgbaData[newIndex + 0] = rgbData[index + 0];
  10740. rgbaData[newIndex + 1] = rgbData[index + 1];
  10741. rgbaData[newIndex + 2] = rgbData[index + 2];
  10742. // Add fully opaque alpha channel.
  10743. rgbaData[newIndex + 3] = 1;
  10744. }
  10745. }
  10746. return rgbaData;
  10747. };
  10748. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10749. var gl = this._gl;
  10750. if (texture._framebuffer) {
  10751. gl.deleteFramebuffer(texture._framebuffer);
  10752. texture._framebuffer = null;
  10753. }
  10754. if (texture._depthStencilBuffer) {
  10755. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10756. texture._depthStencilBuffer = null;
  10757. }
  10758. if (texture._MSAAFramebuffer) {
  10759. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10760. texture._MSAAFramebuffer = null;
  10761. }
  10762. if (texture._MSAARenderBuffer) {
  10763. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10764. texture._MSAARenderBuffer = null;
  10765. }
  10766. };
  10767. Engine.prototype._releaseTexture = function (texture) {
  10768. var gl = this._gl;
  10769. this._releaseFramebufferObjects(texture);
  10770. gl.deleteTexture(texture._webGLTexture);
  10771. // Unbind channels
  10772. this.unbindAllTextures();
  10773. var index = this._internalTexturesCache.indexOf(texture);
  10774. if (index !== -1) {
  10775. this._internalTexturesCache.splice(index, 1);
  10776. }
  10777. // Integrated fixed lod samplers.
  10778. if (texture._lodTextureHigh) {
  10779. texture._lodTextureHigh.dispose();
  10780. }
  10781. if (texture._lodTextureMid) {
  10782. texture._lodTextureMid.dispose();
  10783. }
  10784. if (texture._lodTextureLow) {
  10785. texture._lodTextureLow.dispose();
  10786. }
  10787. };
  10788. Engine.prototype.setProgram = function (program) {
  10789. if (this._currentProgram !== program) {
  10790. this._gl.useProgram(program);
  10791. this._currentProgram = program;
  10792. }
  10793. };
  10794. Engine.prototype.bindSamplers = function (effect) {
  10795. this.setProgram(effect.getProgram());
  10796. var samplers = effect.getSamplers();
  10797. for (var index = 0; index < samplers.length; index++) {
  10798. var uniform = effect.getUniform(samplers[index]);
  10799. this._gl.uniform1i(uniform, index);
  10800. }
  10801. this._currentEffect = null;
  10802. };
  10803. Engine.prototype.activateTexture = function (texture) {
  10804. if (this._activeTexture !== texture) {
  10805. this._gl.activeTexture(texture);
  10806. this._activeTexture = texture;
  10807. }
  10808. };
  10809. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10810. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10811. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10812. this._activeTexturesCache[this._activeTexture] = texture;
  10813. }
  10814. };
  10815. Engine.prototype._bindTexture = function (channel, texture) {
  10816. if (channel < 0) {
  10817. return;
  10818. }
  10819. this.activateTexture(this._gl.TEXTURE0 + channel);
  10820. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10821. };
  10822. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10823. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10824. };
  10825. Engine.prototype.unbindAllTextures = function () {
  10826. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10827. this.activateTexture(this._gl["TEXTURE" + channel]);
  10828. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10829. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10830. }
  10831. };
  10832. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10833. if (channel < 0) {
  10834. return;
  10835. }
  10836. this._gl.uniform1i(uniform, channel);
  10837. this._setTexture(channel, texture);
  10838. };
  10839. Engine.prototype._setTexture = function (channel, texture) {
  10840. // Not ready?
  10841. if (!texture) {
  10842. if (this._activeTexturesCache[channel] != null) {
  10843. this.activateTexture(this._gl["TEXTURE" + channel]);
  10844. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10845. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10846. }
  10847. return;
  10848. }
  10849. // Video
  10850. var alreadyActivated = false;
  10851. if (texture.video) {
  10852. this.activateTexture(this._gl["TEXTURE" + channel]);
  10853. alreadyActivated = true;
  10854. texture.update();
  10855. }
  10856. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10857. texture.delayLoad();
  10858. return;
  10859. }
  10860. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10861. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10862. if (this._activeTexturesCache[channel] === internalTexture) {
  10863. return;
  10864. }
  10865. if (!alreadyActivated) {
  10866. this.activateTexture(this._gl["TEXTURE" + channel]);
  10867. }
  10868. if (internalTexture.isCube) {
  10869. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10870. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10871. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10872. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10873. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10874. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10875. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10876. }
  10877. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10878. }
  10879. else {
  10880. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10881. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10882. internalTexture._cachedWrapU = texture.wrapU;
  10883. switch (texture.wrapU) {
  10884. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10885. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10886. break;
  10887. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10888. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10889. break;
  10890. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10891. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10892. break;
  10893. }
  10894. }
  10895. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10896. internalTexture._cachedWrapV = texture.wrapV;
  10897. switch (texture.wrapV) {
  10898. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10899. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10900. break;
  10901. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10902. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10903. break;
  10904. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10905. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10906. break;
  10907. }
  10908. }
  10909. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10910. }
  10911. };
  10912. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10913. if (channel < 0) {
  10914. return;
  10915. }
  10916. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10917. this._textureUnits = new Int32Array(textures.length);
  10918. }
  10919. for (var i = 0; i < textures.length; i++) {
  10920. this._textureUnits[i] = channel + i;
  10921. }
  10922. this._gl.uniform1iv(uniform, this._textureUnits);
  10923. for (var index = 0; index < textures.length; index++) {
  10924. this._setTexture(channel + index, textures[index]);
  10925. }
  10926. };
  10927. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10928. var internalTexture = texture.getInternalTexture();
  10929. if (!internalTexture) {
  10930. return;
  10931. }
  10932. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10933. var value = texture.anisotropicFilteringLevel;
  10934. if (internalTexture.samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10935. value = 1;
  10936. }
  10937. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  10938. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10939. internalTexture._cachedAnisotropicFilteringLevel = value;
  10940. }
  10941. };
  10942. Engine.prototype.readPixels = function (x, y, width, height) {
  10943. var data = new Uint8Array(height * width * 4);
  10944. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10945. return data;
  10946. };
  10947. /**
  10948. * Add an externaly attached data from its key.
  10949. * This method call will fail and return false, if such key already exists.
  10950. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10951. * @param key the unique key that identifies the data
  10952. * @param data the data object to associate to the key for this Engine instance
  10953. * @return true if no such key were already present and the data was added successfully, false otherwise
  10954. */
  10955. Engine.prototype.addExternalData = function (key, data) {
  10956. if (!this._externalData) {
  10957. this._externalData = new BABYLON.StringDictionary();
  10958. }
  10959. return this._externalData.add(key, data);
  10960. };
  10961. /**
  10962. * Get an externaly attached data from its key
  10963. * @param key the unique key that identifies the data
  10964. * @return the associated data, if present (can be null), or undefined if not present
  10965. */
  10966. Engine.prototype.getExternalData = function (key) {
  10967. if (!this._externalData) {
  10968. this._externalData = new BABYLON.StringDictionary();
  10969. }
  10970. return this._externalData.get(key);
  10971. };
  10972. /**
  10973. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10974. * @param key the unique key that identifies the data
  10975. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10976. * @return the associated data, can be null if the factory returned null.
  10977. */
  10978. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10979. if (!this._externalData) {
  10980. this._externalData = new BABYLON.StringDictionary();
  10981. }
  10982. return this._externalData.getOrAddWithFactory(key, factory);
  10983. };
  10984. /**
  10985. * Remove an externaly attached data from the Engine instance
  10986. * @param key the unique key that identifies the data
  10987. * @return true if the data was successfully removed, false if it doesn't exist
  10988. */
  10989. Engine.prototype.removeExternalData = function (key) {
  10990. if (!this._externalData) {
  10991. this._externalData = new BABYLON.StringDictionary();
  10992. }
  10993. return this._externalData.remove(key);
  10994. };
  10995. Engine.prototype.unbindAllAttributes = function () {
  10996. if (this._mustWipeVertexAttributes) {
  10997. this._mustWipeVertexAttributes = false;
  10998. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10999. this._gl.disableVertexAttribArray(i);
  11000. this._vertexAttribArraysEnabled[i] = false;
  11001. this._currentBufferPointers[i].active = false;
  11002. }
  11003. return;
  11004. }
  11005. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11006. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11007. continue;
  11008. }
  11009. this._gl.disableVertexAttribArray(i);
  11010. this._vertexAttribArraysEnabled[i] = false;
  11011. this._currentBufferPointers[i].active = false;
  11012. }
  11013. };
  11014. Engine.prototype.releaseEffects = function () {
  11015. for (var name in this._compiledEffects) {
  11016. this._gl.deleteProgram(this._compiledEffects[name]._program);
  11017. }
  11018. this._compiledEffects = {};
  11019. };
  11020. // Dispose
  11021. Engine.prototype.dispose = function () {
  11022. this.hideLoadingUI();
  11023. this.stopRenderLoop();
  11024. // Release postProcesses
  11025. while (this.postProcesses.length) {
  11026. this.postProcesses[0].dispose();
  11027. }
  11028. // Empty texture
  11029. if (this._emptyTexture) {
  11030. this._releaseTexture(this._emptyTexture);
  11031. this._emptyTexture = null;
  11032. }
  11033. if (this._emptyCubeTexture) {
  11034. this._releaseTexture(this._emptyCubeTexture);
  11035. this._emptyCubeTexture = null;
  11036. }
  11037. // Rescale PP
  11038. if (this._rescalePostProcess) {
  11039. this._rescalePostProcess.dispose();
  11040. }
  11041. // Release scenes
  11042. while (this.scenes.length) {
  11043. this.scenes[0].dispose();
  11044. }
  11045. // Release audio engine
  11046. if (Engine.audioEngine) {
  11047. Engine.audioEngine.dispose();
  11048. }
  11049. // Release effects
  11050. this.releaseEffects();
  11051. // Unbind
  11052. this.unbindAllAttributes();
  11053. if (this._dummyFramebuffer) {
  11054. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11055. }
  11056. this._gl = null;
  11057. //WebVR
  11058. this.disableVR();
  11059. // Events
  11060. window.removeEventListener("blur", this._onBlur);
  11061. window.removeEventListener("focus", this._onFocus);
  11062. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11063. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11064. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11065. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11066. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11067. if (!this._doNotHandleContextLost) {
  11068. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11069. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11070. }
  11071. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11072. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11073. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11074. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11075. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11076. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11077. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11078. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11079. // Remove from Instances
  11080. var index = Engine.Instances.indexOf(this);
  11081. if (index >= 0) {
  11082. Engine.Instances.splice(index, 1);
  11083. }
  11084. this._workingCanvas = null;
  11085. this._workingContext = null;
  11086. this._currentBufferPointers = null;
  11087. this._renderingCanvas = null;
  11088. this._currentProgram = null;
  11089. this.onResizeObservable.clear();
  11090. this.onCanvasBlurObservable.clear();
  11091. this.onCanvasFocusObservable.clear();
  11092. this.onCanvasPointerOutObservable.clear();
  11093. BABYLON.Effect.ResetCache();
  11094. };
  11095. // Loading screen
  11096. Engine.prototype.displayLoadingUI = function () {
  11097. var loadingScreen = this.loadingScreen;
  11098. if (loadingScreen) {
  11099. loadingScreen.displayLoadingUI();
  11100. }
  11101. };
  11102. Engine.prototype.hideLoadingUI = function () {
  11103. var loadingScreen = this.loadingScreen;
  11104. if (loadingScreen) {
  11105. loadingScreen.hideLoadingUI();
  11106. }
  11107. };
  11108. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11109. get: function () {
  11110. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  11111. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11112. return this._loadingScreen;
  11113. },
  11114. set: function (loadingScreen) {
  11115. this._loadingScreen = loadingScreen;
  11116. },
  11117. enumerable: true,
  11118. configurable: true
  11119. });
  11120. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11121. set: function (text) {
  11122. this.loadingScreen.loadingUIText = text;
  11123. },
  11124. enumerable: true,
  11125. configurable: true
  11126. });
  11127. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11128. set: function (color) {
  11129. this.loadingScreen.loadingUIBackgroundColor = color;
  11130. },
  11131. enumerable: true,
  11132. configurable: true
  11133. });
  11134. Engine.prototype.attachContextLostEvent = function (callback) {
  11135. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11136. };
  11137. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11138. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11139. };
  11140. Engine.prototype.getVertexShaderSource = function (program) {
  11141. var shaders = this._gl.getAttachedShaders(program);
  11142. return this._gl.getShaderSource(shaders[0]);
  11143. };
  11144. Engine.prototype.getFragmentShaderSource = function (program) {
  11145. var shaders = this._gl.getAttachedShaders(program);
  11146. return this._gl.getShaderSource(shaders[1]);
  11147. };
  11148. Engine.prototype.getError = function () {
  11149. return this._gl.getError();
  11150. };
  11151. // FPS
  11152. Engine.prototype.getFps = function () {
  11153. return this._fps;
  11154. };
  11155. Engine.prototype.getDeltaTime = function () {
  11156. return this._deltaTime;
  11157. };
  11158. Engine.prototype._measureFps = function () {
  11159. this._performanceMonitor.sampleFrame();
  11160. this._fps = this._performanceMonitor.averageFPS;
  11161. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11162. };
  11163. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11164. if (faceIndex === void 0) { faceIndex = -1; }
  11165. var gl = this._gl;
  11166. if (!this._dummyFramebuffer) {
  11167. this._dummyFramebuffer = gl.createFramebuffer();
  11168. }
  11169. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11170. if (faceIndex > -1) {
  11171. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11172. }
  11173. else {
  11174. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11175. }
  11176. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11177. var buffer;
  11178. switch (readType) {
  11179. case gl.UNSIGNED_BYTE:
  11180. buffer = new Uint8Array(4 * width * height);
  11181. readType = gl.UNSIGNED_BYTE;
  11182. break;
  11183. default:
  11184. buffer = new Float32Array(4 * width * height);
  11185. readType = gl.FLOAT;
  11186. break;
  11187. }
  11188. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11189. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11190. return buffer;
  11191. };
  11192. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11193. if (this._webGLVersion > 1) {
  11194. return this._caps.colorBufferFloat;
  11195. }
  11196. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11197. };
  11198. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11199. if (this._webGLVersion > 1) {
  11200. return this._caps.colorBufferFloat;
  11201. }
  11202. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11203. };
  11204. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11205. Engine.prototype._canRenderToFramebuffer = function (type) {
  11206. var gl = this._gl;
  11207. //clear existing errors
  11208. while (gl.getError() !== gl.NO_ERROR) { }
  11209. var successful = true;
  11210. var texture = gl.createTexture();
  11211. gl.bindTexture(gl.TEXTURE_2D, texture);
  11212. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11213. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11214. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11215. var fb = gl.createFramebuffer();
  11216. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11217. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11218. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11219. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11220. successful = successful && (gl.getError() === gl.NO_ERROR);
  11221. //try render by clearing frame buffer's color buffer
  11222. if (successful) {
  11223. gl.clear(gl.COLOR_BUFFER_BIT);
  11224. successful = successful && (gl.getError() === gl.NO_ERROR);
  11225. }
  11226. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11227. if (successful) {
  11228. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11229. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11230. var readFormat = gl.RGBA;
  11231. var readType = gl.UNSIGNED_BYTE;
  11232. var buffer = new Uint8Array(4);
  11233. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11234. successful = successful && (gl.getError() === gl.NO_ERROR);
  11235. }
  11236. //clean up
  11237. gl.deleteTexture(texture);
  11238. gl.deleteFramebuffer(fb);
  11239. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11240. //clear accumulated errors
  11241. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11242. return successful;
  11243. };
  11244. Engine.prototype._getWebGLTextureType = function (type) {
  11245. if (type === Engine.TEXTURETYPE_FLOAT) {
  11246. return this._gl.FLOAT;
  11247. }
  11248. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11249. // Add Half Float Constant.
  11250. return this._gl.HALF_FLOAT_OES;
  11251. }
  11252. return this._gl.UNSIGNED_BYTE;
  11253. };
  11254. ;
  11255. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11256. if (this._webGLVersion === 1) {
  11257. return this._gl.RGBA;
  11258. }
  11259. if (type === Engine.TEXTURETYPE_FLOAT) {
  11260. return this._gl.RGBA32F;
  11261. }
  11262. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11263. return this._gl.RGBA16F;
  11264. }
  11265. return this._gl.RGBA;
  11266. };
  11267. ;
  11268. Engine.prototype.createQuery = function () {
  11269. return this._gl.createQuery();
  11270. };
  11271. Engine.prototype.deleteQuery = function (query) {
  11272. this._gl.deleteQuery(query);
  11273. return this;
  11274. };
  11275. Engine.prototype.isQueryResultAvailable = function (query) {
  11276. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11277. };
  11278. Engine.prototype.getQueryResult = function (query) {
  11279. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11280. };
  11281. Engine.prototype.beginQuery = function (algorithmType, query) {
  11282. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11283. this._gl.beginQuery(glAlgorithm, query);
  11284. };
  11285. Engine.prototype.endQuery = function (algorithmType) {
  11286. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11287. this._gl.endQuery(glAlgorithm);
  11288. return this;
  11289. };
  11290. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11291. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11292. };
  11293. // Statics
  11294. Engine.isSupported = function () {
  11295. try {
  11296. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11297. if (navigator.isCocoonJS) {
  11298. return true;
  11299. }
  11300. var tempcanvas = document.createElement("canvas");
  11301. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11302. return gl != null && !!window.WebGLRenderingContext;
  11303. }
  11304. catch (e) {
  11305. return false;
  11306. }
  11307. };
  11308. Engine.Instances = new Array();
  11309. // Const statics
  11310. Engine._ALPHA_DISABLE = 0;
  11311. Engine._ALPHA_ADD = 1;
  11312. Engine._ALPHA_COMBINE = 2;
  11313. Engine._ALPHA_SUBTRACT = 3;
  11314. Engine._ALPHA_MULTIPLY = 4;
  11315. Engine._ALPHA_MAXIMIZED = 5;
  11316. Engine._ALPHA_ONEONE = 6;
  11317. Engine._ALPHA_PREMULTIPLIED = 7;
  11318. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11319. Engine._ALPHA_INTERPOLATE = 9;
  11320. Engine._ALPHA_SCREENMODE = 10;
  11321. Engine._DELAYLOADSTATE_NONE = 0;
  11322. Engine._DELAYLOADSTATE_LOADED = 1;
  11323. Engine._DELAYLOADSTATE_LOADING = 2;
  11324. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11325. Engine._TEXTUREFORMAT_ALPHA = 0;
  11326. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11327. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11328. Engine._TEXTUREFORMAT_RGB = 4;
  11329. Engine._TEXTUREFORMAT_RGBA = 5;
  11330. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11331. Engine._TEXTURETYPE_FLOAT = 1;
  11332. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11333. // Depht or Stencil test Constants.
  11334. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11335. 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.
  11336. 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.
  11337. 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.
  11338. 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.
  11339. 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.
  11340. 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.
  11341. 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.
  11342. // Stencil Actions Constants.
  11343. Engine._KEEP = 0x1E00;
  11344. Engine._REPLACE = 0x1E01;
  11345. Engine._INCR = 0x1E02;
  11346. Engine._DECR = 0x1E03;
  11347. Engine._INVERT = 0x150A;
  11348. Engine._INCR_WRAP = 0x8507;
  11349. Engine._DECR_WRAP = 0x8508;
  11350. // Texture rescaling mode
  11351. Engine._SCALEMODE_FLOOR = 1;
  11352. Engine._SCALEMODE_NEAREST = 2;
  11353. Engine._SCALEMODE_CEILING = 3;
  11354. // Updatable statics so stick with vars here
  11355. Engine.CollisionsEpsilon = 0.001;
  11356. Engine.CodeRepository = "src/";
  11357. Engine.ShadersRepository = "src/Shaders/";
  11358. return Engine;
  11359. }());
  11360. BABYLON.Engine = Engine;
  11361. })(BABYLON || (BABYLON = {}));
  11362. //# sourceMappingURL=babylon.engine.js.map
  11363. /// <reference path="Tools\babylon.decorators.ts" />
  11364. var BABYLON;
  11365. (function (BABYLON) {
  11366. /**
  11367. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11368. */
  11369. var Node = (function () {
  11370. /**
  11371. * @constructor
  11372. * @param {string} name - the name and id to be given to this node
  11373. * @param {BABYLON.Scene} the scene this node will be added to
  11374. */
  11375. function Node(name, scene) {
  11376. this.state = "";
  11377. this.metadata = null;
  11378. this.doNotSerialize = false;
  11379. this.animations = new Array();
  11380. this._ranges = {};
  11381. this._childrenFlag = -1;
  11382. this._isEnabled = true;
  11383. this._isReady = true;
  11384. this._currentRenderId = -1;
  11385. this._parentRenderId = -1;
  11386. /**
  11387. * An event triggered when the mesh is disposed.
  11388. * @type {BABYLON.Observable}
  11389. */
  11390. this.onDisposeObservable = new BABYLON.Observable();
  11391. // Behaviors
  11392. this._behaviors = new Array();
  11393. this.name = name;
  11394. this.id = name;
  11395. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11396. this._initCache();
  11397. }
  11398. Object.defineProperty(Node.prototype, "parent", {
  11399. get: function () {
  11400. return this._parentNode;
  11401. },
  11402. set: function (parent) {
  11403. if (this._parentNode === parent) {
  11404. return;
  11405. }
  11406. if (this._parentNode) {
  11407. var index = this._parentNode._children.indexOf(this);
  11408. if (index !== -1) {
  11409. this._parentNode._children.splice(index, 1);
  11410. }
  11411. }
  11412. this._parentNode = parent;
  11413. if (this._parentNode) {
  11414. if (!this._parentNode._children) {
  11415. this._parentNode._children = new Array();
  11416. }
  11417. this._parentNode._children.push(this);
  11418. }
  11419. },
  11420. enumerable: true,
  11421. configurable: true
  11422. });
  11423. Node.prototype.getClassName = function () {
  11424. return "Node";
  11425. };
  11426. Object.defineProperty(Node.prototype, "onDispose", {
  11427. set: function (callback) {
  11428. if (this._onDisposeObserver) {
  11429. this.onDisposeObservable.remove(this._onDisposeObserver);
  11430. }
  11431. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11432. },
  11433. enumerable: true,
  11434. configurable: true
  11435. });
  11436. Node.prototype.getScene = function () {
  11437. return this._scene;
  11438. };
  11439. Node.prototype.getEngine = function () {
  11440. return this._scene.getEngine();
  11441. };
  11442. Node.prototype.addBehavior = function (behavior) {
  11443. var index = this._behaviors.indexOf(behavior);
  11444. if (index !== -1) {
  11445. return;
  11446. }
  11447. behavior.attach(this);
  11448. this._behaviors.push(behavior);
  11449. return this;
  11450. };
  11451. Node.prototype.removeBehavior = function (behavior) {
  11452. var index = this._behaviors.indexOf(behavior);
  11453. if (index === -1) {
  11454. return;
  11455. }
  11456. this._behaviors[index].detach();
  11457. this._behaviors.splice(index, 1);
  11458. return this;
  11459. };
  11460. Object.defineProperty(Node.prototype, "behaviors", {
  11461. get: function () {
  11462. return this._behaviors;
  11463. },
  11464. enumerable: true,
  11465. configurable: true
  11466. });
  11467. Node.prototype.getBehaviorByName = function (name) {
  11468. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11469. var behavior = _a[_i];
  11470. if (behavior.name === name) {
  11471. return behavior;
  11472. }
  11473. }
  11474. return null;
  11475. };
  11476. // override it in derived class
  11477. Node.prototype.getWorldMatrix = function () {
  11478. return BABYLON.Matrix.Identity();
  11479. };
  11480. // override it in derived class if you add new variables to the cache
  11481. // and call the parent class method
  11482. Node.prototype._initCache = function () {
  11483. this._cache = {};
  11484. this._cache.parent = undefined;
  11485. };
  11486. Node.prototype.updateCache = function (force) {
  11487. if (!force && this.isSynchronized())
  11488. return;
  11489. this._cache.parent = this.parent;
  11490. this._updateCache();
  11491. };
  11492. // override it in derived class if you add new variables to the cache
  11493. // and call the parent class method if !ignoreParentClass
  11494. Node.prototype._updateCache = function (ignoreParentClass) {
  11495. };
  11496. // override it in derived class if you add new variables to the cache
  11497. Node.prototype._isSynchronized = function () {
  11498. return true;
  11499. };
  11500. Node.prototype._markSyncedWithParent = function () {
  11501. this._parentRenderId = this.parent._currentRenderId;
  11502. };
  11503. Node.prototype.isSynchronizedWithParent = function () {
  11504. if (!this.parent) {
  11505. return true;
  11506. }
  11507. if (this._parentRenderId !== this.parent._currentRenderId) {
  11508. return false;
  11509. }
  11510. return this.parent.isSynchronized();
  11511. };
  11512. Node.prototype.isSynchronized = function (updateCache) {
  11513. var check = this.hasNewParent();
  11514. check = check || !this.isSynchronizedWithParent();
  11515. check = check || !this._isSynchronized();
  11516. if (updateCache)
  11517. this.updateCache(true);
  11518. return !check;
  11519. };
  11520. Node.prototype.hasNewParent = function (update) {
  11521. if (this._cache.parent === this.parent)
  11522. return false;
  11523. if (update)
  11524. this._cache.parent = this.parent;
  11525. return true;
  11526. };
  11527. /**
  11528. * Is this node ready to be used/rendered
  11529. * @return {boolean} is it ready
  11530. */
  11531. Node.prototype.isReady = function () {
  11532. return this._isReady;
  11533. };
  11534. /**
  11535. * Is this node enabled.
  11536. * If the node has a parent and is enabled, the parent will be inspected as well.
  11537. * @return {boolean} whether this node (and its parent) is enabled.
  11538. * @see setEnabled
  11539. */
  11540. Node.prototype.isEnabled = function () {
  11541. if (!this._isEnabled) {
  11542. return false;
  11543. }
  11544. if (this.parent) {
  11545. return this.parent.isEnabled();
  11546. }
  11547. return true;
  11548. };
  11549. /**
  11550. * Set the enabled state of this node.
  11551. * @param {boolean} value - the new enabled state
  11552. * @see isEnabled
  11553. */
  11554. Node.prototype.setEnabled = function (value) {
  11555. this._isEnabled = value;
  11556. };
  11557. /**
  11558. * Is this node a descendant of the given node.
  11559. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11560. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11561. * @see parent
  11562. */
  11563. Node.prototype.isDescendantOf = function (ancestor) {
  11564. if (this.parent) {
  11565. if (this.parent === ancestor) {
  11566. return true;
  11567. }
  11568. return this.parent.isDescendantOf(ancestor);
  11569. }
  11570. return false;
  11571. };
  11572. /**
  11573. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11574. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11575. * @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.
  11576. * @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.
  11577. */
  11578. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11579. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11580. if (!this._children) {
  11581. return;
  11582. }
  11583. for (var index = 0; index < this._children.length; index++) {
  11584. var item = this._children[index];
  11585. if (!predicate || predicate(item)) {
  11586. results.push(item);
  11587. }
  11588. if (!directDescendantsOnly) {
  11589. item._getDescendants(results, false, predicate);
  11590. }
  11591. }
  11592. };
  11593. /**
  11594. * Will return all nodes that have this node as ascendant.
  11595. * @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.
  11596. * @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.
  11597. * @return {BABYLON.Node[]} all children nodes of all types.
  11598. */
  11599. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11600. var results = [];
  11601. this._getDescendants(results, directDescendantsOnly, predicate);
  11602. return results;
  11603. };
  11604. /**
  11605. * Get all child-meshes of this node.
  11606. */
  11607. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11608. var results = [];
  11609. this._getDescendants(results, directDecendantsOnly, function (node) {
  11610. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11611. });
  11612. return results;
  11613. };
  11614. /**
  11615. * Get all direct children of this node.
  11616. */
  11617. Node.prototype.getChildren = function (predicate) {
  11618. return this.getDescendants(true, predicate);
  11619. };
  11620. Node.prototype._setReady = function (state) {
  11621. if (state === this._isReady) {
  11622. return;
  11623. }
  11624. if (!state) {
  11625. this._isReady = false;
  11626. return;
  11627. }
  11628. this._isReady = true;
  11629. if (this.onReady) {
  11630. this.onReady(this);
  11631. }
  11632. };
  11633. Node.prototype.getAnimationByName = function (name) {
  11634. for (var i = 0; i < this.animations.length; i++) {
  11635. var animation = this.animations[i];
  11636. if (animation.name === name) {
  11637. return animation;
  11638. }
  11639. }
  11640. return null;
  11641. };
  11642. Node.prototype.createAnimationRange = function (name, from, to) {
  11643. // check name not already in use
  11644. if (!this._ranges[name]) {
  11645. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11646. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11647. if (this.animations[i]) {
  11648. this.animations[i].createRange(name, from, to);
  11649. }
  11650. }
  11651. }
  11652. };
  11653. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11654. if (deleteFrames === void 0) { deleteFrames = true; }
  11655. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11656. if (this.animations[i]) {
  11657. this.animations[i].deleteRange(name, deleteFrames);
  11658. }
  11659. }
  11660. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11661. };
  11662. Node.prototype.getAnimationRange = function (name) {
  11663. return this._ranges[name];
  11664. };
  11665. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11666. var range = this.getAnimationRange(name);
  11667. if (!range) {
  11668. return null;
  11669. }
  11670. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11671. };
  11672. Node.prototype.serializeAnimationRanges = function () {
  11673. var serializationRanges = [];
  11674. for (var name in this._ranges) {
  11675. var range = {};
  11676. range.name = name;
  11677. range.from = this._ranges[name].from;
  11678. range.to = this._ranges[name].to;
  11679. serializationRanges.push(range);
  11680. }
  11681. return serializationRanges;
  11682. };
  11683. Node.prototype.dispose = function () {
  11684. this.parent = null;
  11685. // Callback
  11686. this.onDisposeObservable.notifyObservers(this);
  11687. this.onDisposeObservable.clear();
  11688. // Behaviors
  11689. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11690. var behavior = _a[_i];
  11691. behavior.detach();
  11692. }
  11693. this._behaviors = [];
  11694. };
  11695. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11696. if (parsedNode.ranges) {
  11697. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11698. var data = parsedNode.ranges[index];
  11699. node.createAnimationRange(data.name, data.from, data.to);
  11700. }
  11701. }
  11702. };
  11703. __decorate([
  11704. BABYLON.serialize()
  11705. ], Node.prototype, "name", void 0);
  11706. __decorate([
  11707. BABYLON.serialize()
  11708. ], Node.prototype, "id", void 0);
  11709. __decorate([
  11710. BABYLON.serialize()
  11711. ], Node.prototype, "uniqueId", void 0);
  11712. __decorate([
  11713. BABYLON.serialize()
  11714. ], Node.prototype, "state", void 0);
  11715. __decorate([
  11716. BABYLON.serialize()
  11717. ], Node.prototype, "metadata", void 0);
  11718. return Node;
  11719. }());
  11720. BABYLON.Node = Node;
  11721. })(BABYLON || (BABYLON = {}));
  11722. //# sourceMappingURL=babylon.node.js.map
  11723. var BABYLON;
  11724. (function (BABYLON) {
  11725. var BoundingSphere = (function () {
  11726. function BoundingSphere(minimum, maximum) {
  11727. this.minimum = minimum;
  11728. this.maximum = maximum;
  11729. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11730. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11731. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11732. this.radius = distance * 0.5;
  11733. this.centerWorld = BABYLON.Vector3.Zero();
  11734. this._update(BABYLON.Matrix.Identity());
  11735. }
  11736. // Methods
  11737. BoundingSphere.prototype._update = function (world) {
  11738. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11739. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11740. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11741. };
  11742. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11743. for (var i = 0; i < 6; i++) {
  11744. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11745. return false;
  11746. }
  11747. return true;
  11748. };
  11749. BoundingSphere.prototype.intersectsPoint = function (point) {
  11750. var x = this.centerWorld.x - point.x;
  11751. var y = this.centerWorld.y - point.y;
  11752. var z = this.centerWorld.z - point.z;
  11753. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11754. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11755. return false;
  11756. return true;
  11757. };
  11758. // Statics
  11759. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11760. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11761. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11762. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11763. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11764. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11765. return false;
  11766. return true;
  11767. };
  11768. return BoundingSphere;
  11769. }());
  11770. BABYLON.BoundingSphere = BoundingSphere;
  11771. })(BABYLON || (BABYLON = {}));
  11772. //# sourceMappingURL=babylon.boundingSphere.js.map
  11773. var BABYLON;
  11774. (function (BABYLON) {
  11775. var BoundingBox = (function () {
  11776. function BoundingBox(minimum, maximum) {
  11777. this.minimum = minimum;
  11778. this.maximum = maximum;
  11779. this.vectors = new Array();
  11780. this.vectorsWorld = new Array();
  11781. // Bounding vectors
  11782. this.vectors.push(this.minimum.clone());
  11783. this.vectors.push(this.maximum.clone());
  11784. this.vectors.push(this.minimum.clone());
  11785. this.vectors[2].x = this.maximum.x;
  11786. this.vectors.push(this.minimum.clone());
  11787. this.vectors[3].y = this.maximum.y;
  11788. this.vectors.push(this.minimum.clone());
  11789. this.vectors[4].z = this.maximum.z;
  11790. this.vectors.push(this.maximum.clone());
  11791. this.vectors[5].z = this.minimum.z;
  11792. this.vectors.push(this.maximum.clone());
  11793. this.vectors[6].x = this.minimum.x;
  11794. this.vectors.push(this.maximum.clone());
  11795. this.vectors[7].y = this.minimum.y;
  11796. // OBB
  11797. this.center = this.maximum.add(this.minimum).scale(0.5);
  11798. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11799. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11800. // World
  11801. for (var index = 0; index < this.vectors.length; index++) {
  11802. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11803. }
  11804. this.minimumWorld = BABYLON.Vector3.Zero();
  11805. this.maximumWorld = BABYLON.Vector3.Zero();
  11806. this.centerWorld = BABYLON.Vector3.Zero();
  11807. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11808. this._update(BABYLON.Matrix.Identity());
  11809. }
  11810. // Methods
  11811. BoundingBox.prototype.getWorldMatrix = function () {
  11812. return this._worldMatrix;
  11813. };
  11814. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11815. this._worldMatrix.copyFrom(matrix);
  11816. return this;
  11817. };
  11818. BoundingBox.prototype._update = function (world) {
  11819. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11820. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11821. for (var index = 0; index < this.vectors.length; index++) {
  11822. var v = this.vectorsWorld[index];
  11823. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11824. if (v.x < this.minimumWorld.x)
  11825. this.minimumWorld.x = v.x;
  11826. if (v.y < this.minimumWorld.y)
  11827. this.minimumWorld.y = v.y;
  11828. if (v.z < this.minimumWorld.z)
  11829. this.minimumWorld.z = v.z;
  11830. if (v.x > this.maximumWorld.x)
  11831. this.maximumWorld.x = v.x;
  11832. if (v.y > this.maximumWorld.y)
  11833. this.maximumWorld.y = v.y;
  11834. if (v.z > this.maximumWorld.z)
  11835. this.maximumWorld.z = v.z;
  11836. }
  11837. // Extend
  11838. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11839. this.extendSizeWorld.scaleInPlace(0.5);
  11840. // OBB
  11841. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11842. this.centerWorld.scaleInPlace(0.5);
  11843. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11844. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11845. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11846. this._worldMatrix = world;
  11847. };
  11848. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11849. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11850. };
  11851. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11852. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11853. };
  11854. BoundingBox.prototype.intersectsPoint = function (point) {
  11855. var delta = -BABYLON.Epsilon;
  11856. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11857. return false;
  11858. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11859. return false;
  11860. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11861. return false;
  11862. return true;
  11863. };
  11864. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11865. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11866. };
  11867. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11868. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11869. return false;
  11870. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11871. return false;
  11872. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11873. return false;
  11874. return true;
  11875. };
  11876. // Statics
  11877. BoundingBox.Intersects = function (box0, box1) {
  11878. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11879. return false;
  11880. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11881. return false;
  11882. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11883. return false;
  11884. return true;
  11885. };
  11886. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11887. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11888. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11889. return (num <= (sphereRadius * sphereRadius));
  11890. };
  11891. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11892. for (var p = 0; p < 6; p++) {
  11893. for (var i = 0; i < 8; i++) {
  11894. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11895. return false;
  11896. }
  11897. }
  11898. }
  11899. return true;
  11900. };
  11901. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11902. for (var p = 0; p < 6; p++) {
  11903. var inCount = 8;
  11904. for (var i = 0; i < 8; i++) {
  11905. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11906. --inCount;
  11907. }
  11908. else {
  11909. break;
  11910. }
  11911. }
  11912. if (inCount === 0)
  11913. return false;
  11914. }
  11915. return true;
  11916. };
  11917. return BoundingBox;
  11918. }());
  11919. BABYLON.BoundingBox = BoundingBox;
  11920. })(BABYLON || (BABYLON = {}));
  11921. //# sourceMappingURL=babylon.boundingBox.js.map
  11922. var BABYLON;
  11923. (function (BABYLON) {
  11924. var computeBoxExtents = function (axis, box) {
  11925. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11926. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11927. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11928. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11929. var r = r0 + r1 + r2;
  11930. return {
  11931. min: p - r,
  11932. max: p + r
  11933. };
  11934. };
  11935. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11936. var axisOverlap = function (axis, box0, box1) {
  11937. var result0 = computeBoxExtents(axis, box0);
  11938. var result1 = computeBoxExtents(axis, box1);
  11939. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11940. };
  11941. var BoundingInfo = (function () {
  11942. function BoundingInfo(minimum, maximum) {
  11943. this.minimum = minimum;
  11944. this.maximum = maximum;
  11945. this._isLocked = false;
  11946. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11947. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11948. }
  11949. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11950. get: function () {
  11951. return this._isLocked;
  11952. },
  11953. set: function (value) {
  11954. this._isLocked = value;
  11955. },
  11956. enumerable: true,
  11957. configurable: true
  11958. });
  11959. // Methods
  11960. BoundingInfo.prototype.update = function (world) {
  11961. if (this._isLocked) {
  11962. return;
  11963. }
  11964. this.boundingBox._update(world);
  11965. this.boundingSphere._update(world);
  11966. };
  11967. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11968. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11969. return false;
  11970. return this.boundingBox.isInFrustum(frustumPlanes);
  11971. };
  11972. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  11973. /**
  11974. * Gets the world distance between the min and max points of the bounding box
  11975. */
  11976. get: function () {
  11977. var boundingBox = this.boundingBox;
  11978. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  11979. return size.length();
  11980. },
  11981. enumerable: true,
  11982. configurable: true
  11983. });
  11984. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11985. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11986. };
  11987. BoundingInfo.prototype._checkCollision = function (collider) {
  11988. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11989. };
  11990. BoundingInfo.prototype.intersectsPoint = function (point) {
  11991. if (!this.boundingSphere.centerWorld) {
  11992. return false;
  11993. }
  11994. if (!this.boundingSphere.intersectsPoint(point)) {
  11995. return false;
  11996. }
  11997. if (!this.boundingBox.intersectsPoint(point)) {
  11998. return false;
  11999. }
  12000. return true;
  12001. };
  12002. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12003. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12004. return false;
  12005. }
  12006. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12007. return false;
  12008. }
  12009. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12010. return false;
  12011. }
  12012. if (!precise) {
  12013. return true;
  12014. }
  12015. var box0 = this.boundingBox;
  12016. var box1 = boundingInfo.boundingBox;
  12017. if (!axisOverlap(box0.directions[0], box0, box1))
  12018. return false;
  12019. if (!axisOverlap(box0.directions[1], box0, box1))
  12020. return false;
  12021. if (!axisOverlap(box0.directions[2], box0, box1))
  12022. return false;
  12023. if (!axisOverlap(box1.directions[0], box0, box1))
  12024. return false;
  12025. if (!axisOverlap(box1.directions[1], box0, box1))
  12026. return false;
  12027. if (!axisOverlap(box1.directions[2], box0, box1))
  12028. return false;
  12029. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12030. return false;
  12031. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12032. return false;
  12033. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12034. return false;
  12035. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12036. return false;
  12037. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12038. return false;
  12039. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12040. return false;
  12041. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12042. return false;
  12043. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12044. return false;
  12045. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12046. return false;
  12047. return true;
  12048. };
  12049. return BoundingInfo;
  12050. }());
  12051. BABYLON.BoundingInfo = BoundingInfo;
  12052. })(BABYLON || (BABYLON = {}));
  12053. //# sourceMappingURL=babylon.boundingInfo.js.map
  12054. var BABYLON;
  12055. (function (BABYLON) {
  12056. var AbstractMesh = (function (_super) {
  12057. __extends(AbstractMesh, _super);
  12058. // Constructor
  12059. function AbstractMesh(name, scene) {
  12060. var _this = _super.call(this, name, scene) || this;
  12061. _this._facetNb = 0; // facet number
  12062. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12063. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12064. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12065. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12066. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12067. _this._subDiv = {
  12068. max: 1,
  12069. X: 1,
  12070. Y: 1,
  12071. Z: 1
  12072. };
  12073. // Events
  12074. /**
  12075. * An event triggered when this mesh collides with another one
  12076. * @type {BABYLON.Observable}
  12077. */
  12078. _this.onCollideObservable = new BABYLON.Observable();
  12079. /**
  12080. * An event triggered when the collision's position changes
  12081. * @type {BABYLON.Observable}
  12082. */
  12083. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12084. /**
  12085. * An event triggered after the world matrix is updated
  12086. * @type {BABYLON.Observable}
  12087. */
  12088. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12089. /**
  12090. * An event triggered when material is changed
  12091. * @type {BABYLON.Observable}
  12092. */
  12093. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12094. // Properties
  12095. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12096. _this.position = BABYLON.Vector3.Zero();
  12097. /**
  12098. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12099. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12100. * or
  12101. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  12102. * for more info check WebGl documentations
  12103. */
  12104. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12105. /**
  12106. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  12107. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12108. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12109. * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  12110. */
  12111. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12112. /**
  12113. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  12114. * The default value is -1 which means don't break the query and wait till the result.
  12115. */
  12116. _this.occlusionRetryCount = -1;
  12117. _this._occlusionInternalRetryCounter = 0;
  12118. _this._isOccluded = false;
  12119. _this._isOcclusionQueryInProgress = false;
  12120. _this._rotation = BABYLON.Vector3.Zero();
  12121. _this._scaling = BABYLON.Vector3.One();
  12122. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12123. _this.visibility = 1.0;
  12124. _this.alphaIndex = Number.MAX_VALUE;
  12125. _this.infiniteDistance = false;
  12126. _this.isVisible = true;
  12127. _this.isPickable = true;
  12128. _this.showBoundingBox = false;
  12129. _this.showSubMeshesBoundingBox = false;
  12130. _this.isBlocker = false;
  12131. _this.enablePointerMoveEvents = false;
  12132. _this.renderingGroupId = 0;
  12133. _this._receiveShadows = false;
  12134. _this.renderOutline = false;
  12135. _this.outlineColor = BABYLON.Color3.Red();
  12136. _this.outlineWidth = 0.02;
  12137. _this.renderOverlay = false;
  12138. _this.overlayColor = BABYLON.Color3.Red();
  12139. _this.overlayAlpha = 0.5;
  12140. _this._hasVertexAlpha = false;
  12141. _this._useVertexColors = true;
  12142. _this._computeBonesUsingShaders = true;
  12143. _this._numBoneInfluencers = 4;
  12144. _this._applyFog = true;
  12145. _this.scalingDeterminant = 1;
  12146. _this.useOctreeForRenderingSelection = true;
  12147. _this.useOctreeForPicking = true;
  12148. _this.useOctreeForCollisions = true;
  12149. _this._layerMask = 0x0FFFFFFF;
  12150. /**
  12151. * True if the mesh must be rendered in any case.
  12152. */
  12153. _this.alwaysSelectAsActiveMesh = false;
  12154. // Collisions
  12155. _this._checkCollisions = false;
  12156. _this._collisionMask = -1;
  12157. _this._collisionGroup = -1;
  12158. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12159. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12160. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12161. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12162. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12163. // Edges
  12164. _this.edgesWidth = 1;
  12165. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12166. // Cache
  12167. _this._localWorld = BABYLON.Matrix.Zero();
  12168. _this._worldMatrix = BABYLON.Matrix.Zero();
  12169. _this._absolutePosition = BABYLON.Vector3.Zero();
  12170. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12171. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12172. _this._isDirty = false;
  12173. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12174. _this._isDisposed = false;
  12175. _this._renderId = 0;
  12176. _this._intersectionsInProgress = new Array();
  12177. _this._isWorldMatrixFrozen = false;
  12178. _this._unIndexed = false;
  12179. _this._lightSources = new Array();
  12180. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12181. if (collidedMesh === void 0) { collidedMesh = null; }
  12182. //TODO move this to the collision coordinator!
  12183. if (_this.getScene().workerCollisions)
  12184. newPosition.multiplyInPlace(_this._collider.radius);
  12185. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12186. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12187. _this.position.addInPlace(_this._diffPositionForCollisions);
  12188. }
  12189. if (collidedMesh) {
  12190. _this.onCollideObservable.notifyObservers(collidedMesh);
  12191. }
  12192. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12193. };
  12194. _this.getScene().addMesh(_this);
  12195. _this._resyncLightSources();
  12196. return _this;
  12197. }
  12198. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12199. get: function () {
  12200. return AbstractMesh._BILLBOARDMODE_NONE;
  12201. },
  12202. enumerable: true,
  12203. configurable: true
  12204. });
  12205. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12206. get: function () {
  12207. return AbstractMesh._BILLBOARDMODE_X;
  12208. },
  12209. enumerable: true,
  12210. configurable: true
  12211. });
  12212. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12213. get: function () {
  12214. return AbstractMesh._BILLBOARDMODE_Y;
  12215. },
  12216. enumerable: true,
  12217. configurable: true
  12218. });
  12219. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12220. get: function () {
  12221. return AbstractMesh._BILLBOARDMODE_Z;
  12222. },
  12223. enumerable: true,
  12224. configurable: true
  12225. });
  12226. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12227. get: function () {
  12228. return AbstractMesh._BILLBOARDMODE_ALL;
  12229. },
  12230. enumerable: true,
  12231. configurable: true
  12232. });
  12233. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12234. /**
  12235. * Read-only : the number of facets in the mesh
  12236. */
  12237. get: function () {
  12238. return this._facetNb;
  12239. },
  12240. enumerable: true,
  12241. configurable: true
  12242. });
  12243. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12244. /**
  12245. * The number (integer) of subdivisions per axis in the partioning space
  12246. */
  12247. get: function () {
  12248. return this._partitioningSubdivisions;
  12249. },
  12250. set: function (nb) {
  12251. this._partitioningSubdivisions = nb;
  12252. },
  12253. enumerable: true,
  12254. configurable: true
  12255. });
  12256. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12257. /**
  12258. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12259. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12260. */
  12261. get: function () {
  12262. return this._partitioningBBoxRatio;
  12263. },
  12264. set: function (ratio) {
  12265. this._partitioningBBoxRatio = ratio;
  12266. },
  12267. enumerable: true,
  12268. configurable: true
  12269. });
  12270. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12271. /**
  12272. * Read-only boolean : is the feature facetData enabled ?
  12273. */
  12274. get: function () {
  12275. return this._facetDataEnabled;
  12276. },
  12277. enumerable: true,
  12278. configurable: true
  12279. });
  12280. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12281. set: function (callback) {
  12282. if (this._onCollideObserver) {
  12283. this.onCollideObservable.remove(this._onCollideObserver);
  12284. }
  12285. this._onCollideObserver = this.onCollideObservable.add(callback);
  12286. },
  12287. enumerable: true,
  12288. configurable: true
  12289. });
  12290. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12291. set: function (callback) {
  12292. if (this._onCollisionPositionChangeObserver) {
  12293. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12294. }
  12295. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12296. },
  12297. enumerable: true,
  12298. configurable: true
  12299. });
  12300. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12301. /**
  12302. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  12303. */
  12304. get: function () {
  12305. return this._isOccluded;
  12306. },
  12307. set: function (value) {
  12308. this._isOccluded = value;
  12309. },
  12310. enumerable: true,
  12311. configurable: true
  12312. });
  12313. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12314. /**
  12315. * Flag to check the progress status of the query
  12316. */
  12317. get: function () {
  12318. return this._isOcclusionQueryInProgress;
  12319. },
  12320. enumerable: true,
  12321. configurable: true
  12322. });
  12323. Object.defineProperty(AbstractMesh.prototype, "material", {
  12324. get: function () {
  12325. return this._material;
  12326. },
  12327. set: function (value) {
  12328. if (this._material === value) {
  12329. return;
  12330. }
  12331. this._material = value;
  12332. if (this.onMaterialChangedObservable.hasObservers) {
  12333. this.onMaterialChangedObservable.notifyObservers(this);
  12334. }
  12335. if (!this.subMeshes) {
  12336. return;
  12337. }
  12338. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12339. var subMesh = _a[_i];
  12340. subMesh.setEffect(null);
  12341. }
  12342. },
  12343. enumerable: true,
  12344. configurable: true
  12345. });
  12346. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12347. get: function () {
  12348. return this._receiveShadows;
  12349. },
  12350. set: function (value) {
  12351. if (this._receiveShadows === value) {
  12352. return;
  12353. }
  12354. this._receiveShadows = value;
  12355. this._markSubMeshesAsLightDirty();
  12356. },
  12357. enumerable: true,
  12358. configurable: true
  12359. });
  12360. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12361. get: function () {
  12362. return this._hasVertexAlpha;
  12363. },
  12364. set: function (value) {
  12365. if (this._hasVertexAlpha === value) {
  12366. return;
  12367. }
  12368. this._hasVertexAlpha = value;
  12369. this._markSubMeshesAsAttributesDirty();
  12370. },
  12371. enumerable: true,
  12372. configurable: true
  12373. });
  12374. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12375. get: function () {
  12376. return this._useVertexColors;
  12377. },
  12378. set: function (value) {
  12379. if (this._useVertexColors === value) {
  12380. return;
  12381. }
  12382. this._useVertexColors = value;
  12383. this._markSubMeshesAsAttributesDirty();
  12384. },
  12385. enumerable: true,
  12386. configurable: true
  12387. });
  12388. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12389. get: function () {
  12390. return this._computeBonesUsingShaders;
  12391. },
  12392. set: function (value) {
  12393. if (this._computeBonesUsingShaders === value) {
  12394. return;
  12395. }
  12396. this._computeBonesUsingShaders = value;
  12397. this._markSubMeshesAsAttributesDirty();
  12398. },
  12399. enumerable: true,
  12400. configurable: true
  12401. });
  12402. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12403. get: function () {
  12404. return this._numBoneInfluencers;
  12405. },
  12406. set: function (value) {
  12407. if (this._numBoneInfluencers === value) {
  12408. return;
  12409. }
  12410. this._numBoneInfluencers = value;
  12411. this._markSubMeshesAsAttributesDirty();
  12412. },
  12413. enumerable: true,
  12414. configurable: true
  12415. });
  12416. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12417. get: function () {
  12418. return this._applyFog;
  12419. },
  12420. set: function (value) {
  12421. if (this._applyFog === value) {
  12422. return;
  12423. }
  12424. this._applyFog = value;
  12425. this._markSubMeshesAsMiscDirty();
  12426. },
  12427. enumerable: true,
  12428. configurable: true
  12429. });
  12430. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12431. get: function () {
  12432. return this._layerMask;
  12433. },
  12434. set: function (value) {
  12435. if (value === this._layerMask) {
  12436. return;
  12437. }
  12438. this._layerMask = value;
  12439. this._resyncLightSources();
  12440. },
  12441. enumerable: true,
  12442. configurable: true
  12443. });
  12444. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12445. get: function () {
  12446. return this._collisionMask;
  12447. },
  12448. set: function (mask) {
  12449. this._collisionMask = !isNaN(mask) ? mask : -1;
  12450. },
  12451. enumerable: true,
  12452. configurable: true
  12453. });
  12454. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12455. get: function () {
  12456. return this._collisionGroup;
  12457. },
  12458. set: function (mask) {
  12459. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12460. },
  12461. enumerable: true,
  12462. configurable: true
  12463. });
  12464. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12465. get: function () {
  12466. return null;
  12467. },
  12468. enumerable: true,
  12469. configurable: true
  12470. });
  12471. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12472. get: function () {
  12473. return this._skeleton;
  12474. },
  12475. set: function (value) {
  12476. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12477. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12478. }
  12479. if (value && value.needInitialSkinMatrix) {
  12480. value._registerMeshWithPoseMatrix(this);
  12481. }
  12482. this._skeleton = value;
  12483. if (!this._skeleton) {
  12484. this._bonesTransformMatrices = null;
  12485. }
  12486. this._markSubMeshesAsAttributesDirty();
  12487. },
  12488. enumerable: true,
  12489. configurable: true
  12490. });
  12491. /**
  12492. * Boolean : true if the mesh has been disposed.
  12493. */
  12494. AbstractMesh.prototype.isDisposed = function () {
  12495. return this._isDisposed;
  12496. };
  12497. /**
  12498. * Returns the string "AbstractMesh"
  12499. */
  12500. AbstractMesh.prototype.getClassName = function () {
  12501. return "AbstractMesh";
  12502. };
  12503. /**
  12504. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12505. */
  12506. AbstractMesh.prototype.toString = function (fullDetails) {
  12507. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12508. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12509. if (this._skeleton) {
  12510. ret += ", skeleton: " + this._skeleton.name;
  12511. }
  12512. if (fullDetails) {
  12513. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12514. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12515. }
  12516. return ret;
  12517. };
  12518. AbstractMesh.prototype._rebuild = function () {
  12519. if (this._occlusionQuery) {
  12520. this._occlusionQuery = null;
  12521. }
  12522. if (this._edgesRenderer) {
  12523. this._edgesRenderer._rebuild();
  12524. }
  12525. if (!this.subMeshes) {
  12526. return;
  12527. }
  12528. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12529. var subMesh = _a[_i];
  12530. subMesh._rebuild();
  12531. }
  12532. };
  12533. AbstractMesh.prototype._resyncLightSources = function () {
  12534. this._lightSources.length = 0;
  12535. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12536. var light = _a[_i];
  12537. if (!light.isEnabled()) {
  12538. continue;
  12539. }
  12540. if (light.canAffectMesh(this)) {
  12541. this._lightSources.push(light);
  12542. }
  12543. }
  12544. this._markSubMeshesAsLightDirty();
  12545. };
  12546. AbstractMesh.prototype._resyncLighSource = function (light) {
  12547. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12548. var index = this._lightSources.indexOf(light);
  12549. if (index === -1) {
  12550. if (!isIn) {
  12551. return;
  12552. }
  12553. this._lightSources.push(light);
  12554. }
  12555. else {
  12556. if (isIn) {
  12557. return;
  12558. }
  12559. this._lightSources.splice(index, 1);
  12560. }
  12561. this._markSubMeshesAsLightDirty();
  12562. };
  12563. AbstractMesh.prototype._removeLightSource = function (light) {
  12564. var index = this._lightSources.indexOf(light);
  12565. if (index === -1) {
  12566. return;
  12567. }
  12568. this._lightSources.splice(index, 1);
  12569. };
  12570. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12571. if (!this.subMeshes) {
  12572. return;
  12573. }
  12574. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12575. var subMesh = _a[_i];
  12576. if (subMesh._materialDefines) {
  12577. func(subMesh._materialDefines);
  12578. }
  12579. }
  12580. };
  12581. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12582. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12583. };
  12584. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12585. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12586. };
  12587. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12588. if (!this.subMeshes) {
  12589. return;
  12590. }
  12591. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12592. var subMesh = _a[_i];
  12593. var material = subMesh.getMaterial();
  12594. if (material) {
  12595. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12596. }
  12597. }
  12598. };
  12599. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12600. /**
  12601. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12602. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12603. * Default : (0.0, 0.0, 0.0)
  12604. */
  12605. get: function () {
  12606. return this._rotation;
  12607. },
  12608. set: function (newRotation) {
  12609. this._rotation = newRotation;
  12610. },
  12611. enumerable: true,
  12612. configurable: true
  12613. });
  12614. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12615. /**
  12616. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12617. * Default : (1.0, 1.0, 1.0)
  12618. */
  12619. get: function () {
  12620. return this._scaling;
  12621. },
  12622. set: function (newScaling) {
  12623. this._scaling = newScaling;
  12624. if (this.physicsImpostor) {
  12625. this.physicsImpostor.forceUpdate();
  12626. }
  12627. },
  12628. enumerable: true,
  12629. configurable: true
  12630. });
  12631. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12632. /**
  12633. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12634. * It's null by default.
  12635. * 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)
  12636. */
  12637. get: function () {
  12638. return this._rotationQuaternion;
  12639. },
  12640. set: function (quaternion) {
  12641. this._rotationQuaternion = quaternion;
  12642. //reset the rotation vector.
  12643. if (quaternion && this.rotation.length()) {
  12644. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12645. }
  12646. },
  12647. enumerable: true,
  12648. configurable: true
  12649. });
  12650. // Methods
  12651. /**
  12652. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12653. * Returns the AbstractMesh.
  12654. */
  12655. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12656. this._poseMatrix.copyFrom(matrix);
  12657. return this;
  12658. };
  12659. /**
  12660. * Returns the mesh Pose matrix.
  12661. * Returned object : Matrix
  12662. */
  12663. AbstractMesh.prototype.getPoseMatrix = function () {
  12664. return this._poseMatrix;
  12665. };
  12666. /**
  12667. * Disables the mesh edger rendering mode.
  12668. * Returns the AbstractMesh.
  12669. */
  12670. AbstractMesh.prototype.disableEdgesRendering = function () {
  12671. if (this._edgesRenderer !== undefined) {
  12672. this._edgesRenderer.dispose();
  12673. this._edgesRenderer = undefined;
  12674. }
  12675. return this;
  12676. };
  12677. /**
  12678. * Enables the edge rendering mode on the mesh.
  12679. * This mode makes the mesh edges visible.
  12680. * Returns the AbstractMesh.
  12681. */
  12682. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12683. if (epsilon === void 0) { epsilon = 0.95; }
  12684. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12685. this.disableEdgesRendering();
  12686. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12687. return this;
  12688. };
  12689. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12690. /**
  12691. * Returns true if the mesh is blocked. Used by the class Mesh.
  12692. * Returns the boolean `false` by default.
  12693. */
  12694. get: function () {
  12695. return false;
  12696. },
  12697. enumerable: true,
  12698. configurable: true
  12699. });
  12700. /**
  12701. * Returns the mesh itself by default, used by the class Mesh.
  12702. * Returned type : AbstractMesh
  12703. */
  12704. AbstractMesh.prototype.getLOD = function (camera) {
  12705. return this;
  12706. };
  12707. /**
  12708. * Returns 0 by default, used by the class Mesh.
  12709. * Returns an integer.
  12710. */
  12711. AbstractMesh.prototype.getTotalVertices = function () {
  12712. return 0;
  12713. };
  12714. /**
  12715. * Returns null by default, used by the class Mesh.
  12716. * Returned type : integer array
  12717. */
  12718. AbstractMesh.prototype.getIndices = function () {
  12719. return null;
  12720. };
  12721. /**
  12722. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12723. * Returned type : float array or Float32Array
  12724. */
  12725. AbstractMesh.prototype.getVerticesData = function (kind) {
  12726. return null;
  12727. };
  12728. /**
  12729. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12730. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12731. * The `data` are either a numeric array either a Float32Array.
  12732. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12733. * 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).
  12734. * Note that a new underlying VertexBuffer object is created each call.
  12735. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12736. *
  12737. * Possible `kind` values :
  12738. * - BABYLON.VertexBuffer.PositionKind
  12739. * - BABYLON.VertexBuffer.UVKind
  12740. * - BABYLON.VertexBuffer.UV2Kind
  12741. * - BABYLON.VertexBuffer.UV3Kind
  12742. * - BABYLON.VertexBuffer.UV4Kind
  12743. * - BABYLON.VertexBuffer.UV5Kind
  12744. * - BABYLON.VertexBuffer.UV6Kind
  12745. * - BABYLON.VertexBuffer.ColorKind
  12746. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12747. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12748. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12749. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12750. *
  12751. * Returns the Mesh.
  12752. */
  12753. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12754. return null;
  12755. };
  12756. /**
  12757. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12758. * If the mesh has no geometry, it is simply returned as it is.
  12759. * The `data` are either a numeric array either a Float32Array.
  12760. * No new underlying VertexBuffer object is created.
  12761. * 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.
  12762. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12763. *
  12764. * Possible `kind` values :
  12765. * - BABYLON.VertexBuffer.PositionKind
  12766. * - BABYLON.VertexBuffer.UVKind
  12767. * - BABYLON.VertexBuffer.UV2Kind
  12768. * - BABYLON.VertexBuffer.UV3Kind
  12769. * - BABYLON.VertexBuffer.UV4Kind
  12770. * - BABYLON.VertexBuffer.UV5Kind
  12771. * - BABYLON.VertexBuffer.UV6Kind
  12772. * - BABYLON.VertexBuffer.ColorKind
  12773. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12774. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12775. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12776. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12777. *
  12778. * Returns the Mesh.
  12779. */
  12780. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12781. return null;
  12782. };
  12783. /**
  12784. * Sets the mesh indices.
  12785. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12786. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12787. * This method creates a new index buffer each call.
  12788. * Returns the Mesh.
  12789. */
  12790. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12791. return null;
  12792. };
  12793. /** Returns false by default, used by the class Mesh.
  12794. * Returns a boolean
  12795. */
  12796. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12797. return false;
  12798. };
  12799. /**
  12800. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12801. * Returns a BoundingInfo
  12802. */
  12803. AbstractMesh.prototype.getBoundingInfo = function () {
  12804. if (this._masterMesh) {
  12805. return this._masterMesh.getBoundingInfo();
  12806. }
  12807. if (!this._boundingInfo) {
  12808. this._updateBoundingInfo();
  12809. }
  12810. return this._boundingInfo;
  12811. };
  12812. /**
  12813. * Sets a mesh new object BoundingInfo.
  12814. * Returns the AbstractMesh.
  12815. */
  12816. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12817. this._boundingInfo = boundingInfo;
  12818. return this;
  12819. };
  12820. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12821. get: function () {
  12822. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12823. },
  12824. enumerable: true,
  12825. configurable: true
  12826. });
  12827. AbstractMesh.prototype._preActivate = function () {
  12828. };
  12829. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12830. };
  12831. AbstractMesh.prototype._activate = function (renderId) {
  12832. this._renderId = renderId;
  12833. };
  12834. /**
  12835. * Returns the last update of the World matrix
  12836. * Returns a Matrix.
  12837. */
  12838. AbstractMesh.prototype.getWorldMatrix = function () {
  12839. if (this._masterMesh) {
  12840. return this._masterMesh.getWorldMatrix();
  12841. }
  12842. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12843. this.computeWorldMatrix();
  12844. }
  12845. return this._worldMatrix;
  12846. };
  12847. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12848. /**
  12849. * Returns directly the last state of the mesh World matrix.
  12850. * A Matrix is returned.
  12851. */
  12852. get: function () {
  12853. return this._worldMatrix;
  12854. },
  12855. enumerable: true,
  12856. configurable: true
  12857. });
  12858. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12859. /**
  12860. * Returns the current mesh absolute position.
  12861. * Retuns a Vector3.
  12862. */
  12863. get: function () {
  12864. return this._absolutePosition;
  12865. },
  12866. enumerable: true,
  12867. configurable: true
  12868. });
  12869. /**
  12870. * Prevents the World matrix to be computed any longer.
  12871. * Returns the AbstractMesh.
  12872. */
  12873. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12874. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12875. this.computeWorldMatrix(true);
  12876. this._isWorldMatrixFrozen = true;
  12877. return this;
  12878. };
  12879. /**
  12880. * Allows back the World matrix computation.
  12881. * Returns the AbstractMesh.
  12882. */
  12883. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12884. this._isWorldMatrixFrozen = false;
  12885. this.computeWorldMatrix(true);
  12886. return this;
  12887. };
  12888. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12889. /**
  12890. * True if the World matrix has been frozen.
  12891. * Returns a boolean.
  12892. */
  12893. get: function () {
  12894. return this._isWorldMatrixFrozen;
  12895. },
  12896. enumerable: true,
  12897. configurable: true
  12898. });
  12899. /**
  12900. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12901. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12902. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12903. * The passed axis is also normalized.
  12904. * Returns the AbstractMesh.
  12905. */
  12906. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12907. axis.normalize();
  12908. if (!this.rotationQuaternion) {
  12909. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12910. this.rotation = BABYLON.Vector3.Zero();
  12911. }
  12912. var rotationQuaternion;
  12913. if (!space || space === BABYLON.Space.LOCAL) {
  12914. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12915. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12916. }
  12917. else {
  12918. if (this.parent) {
  12919. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12920. invertParentWorldMatrix.invert();
  12921. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12922. }
  12923. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12924. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12925. }
  12926. return this;
  12927. };
  12928. /**
  12929. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12930. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12931. * The passed axis is also normalized.
  12932. * Returns the AbstractMesh.
  12933. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12934. */
  12935. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12936. axis.normalize();
  12937. if (!this.rotationQuaternion) {
  12938. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12939. this.rotation.copyFromFloats(0, 0, 0);
  12940. }
  12941. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12942. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12943. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12944. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12945. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12946. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12947. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12948. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12949. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12950. return this;
  12951. };
  12952. /**
  12953. * Translates the mesh along the axis vector for the passed distance in the given space.
  12954. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12955. * Returns the AbstractMesh.
  12956. */
  12957. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12958. var displacementVector = axis.scale(distance);
  12959. if (!space || space === BABYLON.Space.LOCAL) {
  12960. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12961. this.setPositionWithLocalVector(tempV3);
  12962. }
  12963. else {
  12964. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12965. }
  12966. return this;
  12967. };
  12968. /**
  12969. * Adds a rotation step to the mesh current rotation.
  12970. * x, y, z are Euler angles expressed in radians.
  12971. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12972. * This means this rotation is made in the mesh local space only.
  12973. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12974. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12975. * ```javascript
  12976. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12977. * ```
  12978. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12979. * 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.
  12980. * Returns the AbstractMesh.
  12981. */
  12982. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12983. var rotationQuaternion;
  12984. if (this.rotationQuaternion) {
  12985. rotationQuaternion = this.rotationQuaternion;
  12986. }
  12987. else {
  12988. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12989. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12990. }
  12991. var accumulation = BABYLON.Tmp.Quaternion[0];
  12992. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12993. rotationQuaternion.multiplyInPlace(accumulation);
  12994. if (!this.rotationQuaternion) {
  12995. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12996. }
  12997. return this;
  12998. };
  12999. /**
  13000. * Retuns the mesh absolute position in the World.
  13001. * Returns a Vector3.
  13002. */
  13003. AbstractMesh.prototype.getAbsolutePosition = function () {
  13004. this.computeWorldMatrix();
  13005. return this._absolutePosition;
  13006. };
  13007. /**
  13008. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13009. * Returns the AbstractMesh.
  13010. */
  13011. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13012. if (!absolutePosition) {
  13013. return;
  13014. }
  13015. var absolutePositionX;
  13016. var absolutePositionY;
  13017. var absolutePositionZ;
  13018. if (absolutePosition.x === undefined) {
  13019. if (arguments.length < 3) {
  13020. return;
  13021. }
  13022. absolutePositionX = arguments[0];
  13023. absolutePositionY = arguments[1];
  13024. absolutePositionZ = arguments[2];
  13025. }
  13026. else {
  13027. absolutePositionX = absolutePosition.x;
  13028. absolutePositionY = absolutePosition.y;
  13029. absolutePositionZ = absolutePosition.z;
  13030. }
  13031. if (this.parent) {
  13032. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13033. invertParentWorldMatrix.invert();
  13034. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13035. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13036. }
  13037. else {
  13038. this.position.x = absolutePositionX;
  13039. this.position.y = absolutePositionY;
  13040. this.position.z = absolutePositionZ;
  13041. }
  13042. return this;
  13043. };
  13044. // ================================== Point of View Movement =================================
  13045. /**
  13046. * Perform relative position change from the point of view of behind the front of the mesh.
  13047. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13048. * Supports definition of mesh facing forward or backward.
  13049. * @param {number} amountRight
  13050. * @param {number} amountUp
  13051. * @param {number} amountForward
  13052. *
  13053. * Returns the AbstractMesh.
  13054. */
  13055. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13056. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13057. return this;
  13058. };
  13059. /**
  13060. * Calculate relative position change from the point of view of behind the front of the mesh.
  13061. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13062. * Supports definition of mesh facing forward or backward.
  13063. * @param {number} amountRight
  13064. * @param {number} amountUp
  13065. * @param {number} amountForward
  13066. *
  13067. * Returns a new Vector3.
  13068. */
  13069. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13070. var rotMatrix = new BABYLON.Matrix();
  13071. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13072. rotQuaternion.toRotationMatrix(rotMatrix);
  13073. var translationDelta = BABYLON.Vector3.Zero();
  13074. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13075. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13076. return translationDelta;
  13077. };
  13078. // ================================== Point of View Rotation =================================
  13079. /**
  13080. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13081. * Supports definition of mesh facing forward or backward.
  13082. * @param {number} flipBack
  13083. * @param {number} twirlClockwise
  13084. * @param {number} tiltRight
  13085. *
  13086. * Returns the AbstractMesh.
  13087. */
  13088. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13089. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13090. return this;
  13091. };
  13092. /**
  13093. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13094. * Supports definition of mesh facing forward or backward.
  13095. * @param {number} flipBack
  13096. * @param {number} twirlClockwise
  13097. * @param {number} tiltRight
  13098. *
  13099. * Returns a new Vector3.
  13100. */
  13101. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13102. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13103. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13104. };
  13105. /**
  13106. * Sets a new pivot matrix to the mesh.
  13107. * Returns the AbstractMesh.
  13108. */
  13109. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  13110. this._pivotMatrix = matrix;
  13111. this._cache.pivotMatrixUpdated = true;
  13112. return this;
  13113. };
  13114. /**
  13115. * Returns the mesh pivot matrix.
  13116. * Default : Identity.
  13117. * A Matrix is returned.
  13118. */
  13119. AbstractMesh.prototype.getPivotMatrix = function () {
  13120. return this._pivotMatrix;
  13121. };
  13122. AbstractMesh.prototype._isSynchronized = function () {
  13123. if (this._isDirty) {
  13124. return false;
  13125. }
  13126. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13127. return false;
  13128. if (this._cache.pivotMatrixUpdated) {
  13129. return false;
  13130. }
  13131. if (this.infiniteDistance) {
  13132. return false;
  13133. }
  13134. if (!this._cache.position.equals(this.position))
  13135. return false;
  13136. if (this.rotationQuaternion) {
  13137. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13138. return false;
  13139. }
  13140. if (!this._cache.rotation.equals(this.rotation))
  13141. return false;
  13142. if (!this._cache.scaling.equals(this.scaling))
  13143. return false;
  13144. return true;
  13145. };
  13146. AbstractMesh.prototype._initCache = function () {
  13147. _super.prototype._initCache.call(this);
  13148. this._cache.localMatrixUpdated = false;
  13149. this._cache.position = BABYLON.Vector3.Zero();
  13150. this._cache.scaling = BABYLON.Vector3.Zero();
  13151. this._cache.rotation = BABYLON.Vector3.Zero();
  13152. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13153. this._cache.billboardMode = -1;
  13154. };
  13155. AbstractMesh.prototype.markAsDirty = function (property) {
  13156. if (property === "rotation") {
  13157. this.rotationQuaternion = null;
  13158. }
  13159. this._currentRenderId = Number.MAX_VALUE;
  13160. this._isDirty = true;
  13161. return this;
  13162. };
  13163. /**
  13164. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13165. * Returns the AbstractMesh.
  13166. */
  13167. AbstractMesh.prototype._updateBoundingInfo = function () {
  13168. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13169. this._boundingInfo.update(this.worldMatrixFromCache);
  13170. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13171. return this;
  13172. };
  13173. /**
  13174. * Update a mesh's children BoundingInfo objects only.
  13175. * Returns the AbstractMesh.
  13176. */
  13177. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13178. if (!this.subMeshes) {
  13179. return;
  13180. }
  13181. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13182. var subMesh = this.subMeshes[subIndex];
  13183. if (!subMesh.IsGlobal) {
  13184. subMesh.updateBoundingInfo(matrix);
  13185. }
  13186. }
  13187. return this;
  13188. };
  13189. /**
  13190. * Computes the mesh World matrix and returns it.
  13191. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13192. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13193. * If the parameter `force`is set to `true`, the actual computation is done.
  13194. * Returns the mesh World Matrix.
  13195. */
  13196. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13197. if (this._isWorldMatrixFrozen) {
  13198. return this._worldMatrix;
  13199. }
  13200. if (!force && this.isSynchronized(true)) {
  13201. this._currentRenderId = this.getScene().getRenderId();
  13202. return this._worldMatrix;
  13203. }
  13204. this._cache.position.copyFrom(this.position);
  13205. this._cache.scaling.copyFrom(this.scaling);
  13206. this._cache.pivotMatrixUpdated = false;
  13207. this._cache.billboardMode = this.billboardMode;
  13208. this._currentRenderId = this.getScene().getRenderId();
  13209. this._isDirty = false;
  13210. // Scaling
  13211. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13212. // Rotation
  13213. //rotate, if quaternion is set and rotation was used
  13214. if (this.rotationQuaternion) {
  13215. var len = this.rotation.length();
  13216. if (len) {
  13217. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13218. this.rotation.copyFromFloats(0, 0, 0);
  13219. }
  13220. }
  13221. if (this.rotationQuaternion) {
  13222. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13223. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13224. }
  13225. else {
  13226. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13227. this._cache.rotation.copyFrom(this.rotation);
  13228. }
  13229. // Translation
  13230. if (this.infiniteDistance && !this.parent) {
  13231. var camera = this.getScene().activeCamera;
  13232. if (camera) {
  13233. var cameraWorldMatrix = camera.getWorldMatrix();
  13234. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13235. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13236. }
  13237. }
  13238. else {
  13239. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13240. }
  13241. // Composing transformations
  13242. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13243. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13244. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13245. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13246. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13247. // Need to decompose each rotation here
  13248. var currentPosition = BABYLON.Tmp.Vector3[3];
  13249. if (this.parent && this.parent.getWorldMatrix) {
  13250. if (this._meshToBoneReferal) {
  13251. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13252. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13253. }
  13254. else {
  13255. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13256. }
  13257. }
  13258. else {
  13259. currentPosition.copyFrom(this.position);
  13260. }
  13261. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13262. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13263. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13264. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13265. }
  13266. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13267. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13268. }
  13269. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13270. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13271. }
  13272. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13273. }
  13274. else {
  13275. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13276. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13277. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13278. }
  13279. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13280. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13281. }
  13282. // Local world
  13283. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13284. // Parent
  13285. if (this.parent && this.parent.getWorldMatrix) {
  13286. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13287. if (this._meshToBoneReferal) {
  13288. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13289. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13290. }
  13291. else {
  13292. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13293. }
  13294. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13295. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13296. this._worldMatrix.copyFrom(this._localWorld);
  13297. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13298. }
  13299. else {
  13300. if (this._meshToBoneReferal) {
  13301. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13302. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13303. }
  13304. else {
  13305. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13306. }
  13307. }
  13308. this._markSyncedWithParent();
  13309. }
  13310. else {
  13311. this._worldMatrix.copyFrom(this._localWorld);
  13312. }
  13313. // Bounding info
  13314. this._updateBoundingInfo();
  13315. // Absolute position
  13316. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13317. // Callbacks
  13318. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13319. if (!this._poseMatrix) {
  13320. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13321. }
  13322. return this._worldMatrix;
  13323. };
  13324. /**
  13325. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13326. * @param func: callback function to add
  13327. *
  13328. * Returns the AbstractMesh.
  13329. */
  13330. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13331. this.onAfterWorldMatrixUpdateObservable.add(func);
  13332. return this;
  13333. };
  13334. /**
  13335. * Removes a registered callback function.
  13336. * Returns the AbstractMesh.
  13337. */
  13338. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13339. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13340. return this;
  13341. };
  13342. /**
  13343. * Sets the mesh position in its local space.
  13344. * Returns the AbstractMesh.
  13345. */
  13346. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13347. this.computeWorldMatrix();
  13348. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13349. return this;
  13350. };
  13351. /**
  13352. * Returns the mesh position in the local space from the current World matrix values.
  13353. * Returns a new Vector3.
  13354. */
  13355. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13356. this.computeWorldMatrix();
  13357. var invLocalWorldMatrix = this._localWorld.clone();
  13358. invLocalWorldMatrix.invert();
  13359. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13360. };
  13361. /**
  13362. * Translates the mesh along the passed Vector3 in its local space.
  13363. * Returns the AbstractMesh.
  13364. */
  13365. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13366. this.computeWorldMatrix(true);
  13367. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13368. return this;
  13369. };
  13370. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13371. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13372. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13373. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13374. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13375. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13376. /// <returns>Mesh oriented towards targetMesh</returns>
  13377. if (yawCor === void 0) { yawCor = 0; }
  13378. if (pitchCor === void 0) { pitchCor = 0; }
  13379. if (rollCor === void 0) { rollCor = 0; }
  13380. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13381. var dv = AbstractMesh._lookAtVectorCache;
  13382. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13383. targetPoint.subtractToRef(pos, dv);
  13384. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13385. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13386. var pitch = Math.atan2(dv.y, len);
  13387. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13388. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13389. return this;
  13390. };
  13391. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13392. this._meshToBoneReferal = affectedMesh;
  13393. this.parent = bone;
  13394. if (bone.getWorldMatrix().determinant() < 0) {
  13395. this.scalingDeterminant *= -1;
  13396. }
  13397. return this;
  13398. };
  13399. AbstractMesh.prototype.detachFromBone = function () {
  13400. if (this.parent.getWorldMatrix().determinant() < 0) {
  13401. this.scalingDeterminant *= -1;
  13402. }
  13403. this._meshToBoneReferal = null;
  13404. this.parent = null;
  13405. return this;
  13406. };
  13407. /**
  13408. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13409. * A mesh is in the frustum if its bounding box intersects the frustum.
  13410. * Boolean returned.
  13411. */
  13412. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13413. return this._boundingInfo.isInFrustum(frustumPlanes);
  13414. };
  13415. /**
  13416. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13417. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13418. * Boolean returned.
  13419. */
  13420. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13421. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13422. ;
  13423. };
  13424. /**
  13425. * True if the mesh intersects another mesh or a SolidParticle object.
  13426. * 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)
  13427. * Returns a boolean.
  13428. */
  13429. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13430. if (!this._boundingInfo || !mesh._boundingInfo) {
  13431. return false;
  13432. }
  13433. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13434. };
  13435. /**
  13436. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13437. * Returns a boolean.
  13438. */
  13439. AbstractMesh.prototype.intersectsPoint = function (point) {
  13440. if (!this._boundingInfo) {
  13441. return false;
  13442. }
  13443. return this._boundingInfo.intersectsPoint(point);
  13444. };
  13445. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13446. return this.physicsImpostor;
  13447. };
  13448. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13449. if (!camera) {
  13450. camera = this.getScene().activeCamera;
  13451. }
  13452. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13453. };
  13454. /**
  13455. * Returns the distance from the mesh to the active camera.
  13456. * Returns a float.
  13457. */
  13458. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13459. if (!camera) {
  13460. camera = this.getScene().activeCamera;
  13461. }
  13462. return this.absolutePosition.subtract(camera.position).length();
  13463. };
  13464. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13465. if (!this.physicsImpostor) {
  13466. return;
  13467. }
  13468. this.physicsImpostor.applyImpulse(force, contactPoint);
  13469. return this;
  13470. };
  13471. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13472. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13473. return;
  13474. }
  13475. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13476. mainPivot: pivot1,
  13477. connectedPivot: pivot2,
  13478. nativeParams: options
  13479. });
  13480. return this;
  13481. };
  13482. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13483. // Collisions
  13484. /**
  13485. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13486. * Default `false`.
  13487. */
  13488. get: function () {
  13489. return this._checkCollisions;
  13490. },
  13491. set: function (collisionEnabled) {
  13492. this._checkCollisions = collisionEnabled;
  13493. if (this.getScene().workerCollisions) {
  13494. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13495. }
  13496. },
  13497. enumerable: true,
  13498. configurable: true
  13499. });
  13500. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  13501. var globalPosition = this.getAbsolutePosition();
  13502. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13503. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13504. if (!this._collider) {
  13505. this._collider = new BABYLON.Collider();
  13506. }
  13507. this._collider.radius = this.ellipsoid;
  13508. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13509. return this;
  13510. };
  13511. // Submeshes octree
  13512. /**
  13513. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13514. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13515. * Returns an Octree of submeshes.
  13516. */
  13517. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13518. if (maxCapacity === void 0) { maxCapacity = 64; }
  13519. if (maxDepth === void 0) { maxDepth = 2; }
  13520. if (!this._submeshesOctree) {
  13521. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13522. }
  13523. this.computeWorldMatrix(true);
  13524. // Update octree
  13525. var bbox = this.getBoundingInfo().boundingBox;
  13526. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13527. return this._submeshesOctree;
  13528. };
  13529. // Collisions
  13530. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13531. this._generatePointsArray();
  13532. // Transformation
  13533. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13534. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13535. subMesh._lastColliderWorldVertices = [];
  13536. subMesh._trianglePlanes = [];
  13537. var start = subMesh.verticesStart;
  13538. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13539. for (var i = start; i < end; i++) {
  13540. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13541. }
  13542. }
  13543. // Collide
  13544. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13545. if (collider.collisionFound) {
  13546. collider.collidedMesh = this;
  13547. }
  13548. return this;
  13549. };
  13550. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13551. var subMeshes;
  13552. var len;
  13553. // Octrees
  13554. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13555. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13556. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13557. len = intersections.length;
  13558. subMeshes = intersections.data;
  13559. }
  13560. else {
  13561. subMeshes = this.subMeshes;
  13562. len = subMeshes.length;
  13563. }
  13564. for (var index = 0; index < len; index++) {
  13565. var subMesh = subMeshes[index];
  13566. // Bounding test
  13567. if (len > 1 && !subMesh._checkCollision(collider))
  13568. continue;
  13569. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13570. }
  13571. return this;
  13572. };
  13573. AbstractMesh.prototype._checkCollision = function (collider) {
  13574. // Bounding box test
  13575. if (!this._boundingInfo._checkCollision(collider))
  13576. return this;
  13577. // Transformation matrix
  13578. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13579. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13580. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13581. return this;
  13582. };
  13583. // Picking
  13584. AbstractMesh.prototype._generatePointsArray = function () {
  13585. return false;
  13586. };
  13587. /**
  13588. * Checks if the passed Ray intersects with the mesh.
  13589. * Returns an object PickingInfo.
  13590. */
  13591. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13592. var pickingInfo = new BABYLON.PickingInfo();
  13593. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13594. return pickingInfo;
  13595. }
  13596. if (!this._generatePointsArray()) {
  13597. return pickingInfo;
  13598. }
  13599. var intersectInfo = null;
  13600. // Octrees
  13601. var subMeshes;
  13602. var len;
  13603. if (this._submeshesOctree && this.useOctreeForPicking) {
  13604. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13605. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13606. len = intersections.length;
  13607. subMeshes = intersections.data;
  13608. }
  13609. else {
  13610. subMeshes = this.subMeshes;
  13611. len = subMeshes.length;
  13612. }
  13613. for (var index = 0; index < len; index++) {
  13614. var subMesh = subMeshes[index];
  13615. // Bounding test
  13616. if (len > 1 && !subMesh.canIntersects(ray))
  13617. continue;
  13618. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13619. if (currentIntersectInfo) {
  13620. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13621. intersectInfo = currentIntersectInfo;
  13622. intersectInfo.subMeshId = index;
  13623. if (fastCheck) {
  13624. break;
  13625. }
  13626. }
  13627. }
  13628. }
  13629. if (intersectInfo) {
  13630. // Get picked point
  13631. var world = this.getWorldMatrix();
  13632. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13633. var direction = ray.direction.clone();
  13634. direction = direction.scale(intersectInfo.distance);
  13635. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13636. var pickedPoint = worldOrigin.add(worldDirection);
  13637. // Return result
  13638. pickingInfo.hit = true;
  13639. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13640. pickingInfo.pickedPoint = pickedPoint;
  13641. pickingInfo.pickedMesh = this;
  13642. pickingInfo.bu = intersectInfo.bu;
  13643. pickingInfo.bv = intersectInfo.bv;
  13644. pickingInfo.faceId = intersectInfo.faceId;
  13645. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13646. return pickingInfo;
  13647. }
  13648. return pickingInfo;
  13649. };
  13650. /**
  13651. * Clones the mesh, used by the class Mesh.
  13652. * Just returns `null` for an AbstractMesh.
  13653. */
  13654. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13655. return null;
  13656. };
  13657. /**
  13658. * Disposes all the mesh submeshes.
  13659. * Returns the AbstractMesh.
  13660. */
  13661. AbstractMesh.prototype.releaseSubMeshes = function () {
  13662. if (this.subMeshes) {
  13663. while (this.subMeshes.length) {
  13664. this.subMeshes[0].dispose();
  13665. }
  13666. }
  13667. else {
  13668. this.subMeshes = new Array();
  13669. }
  13670. return this;
  13671. };
  13672. /**
  13673. * Disposes the AbstractMesh.
  13674. * Some internal references are kept for further use.
  13675. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13676. * Returns nothing.
  13677. */
  13678. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13679. var _this = this;
  13680. var index;
  13681. // Action manager
  13682. if (this.actionManager) {
  13683. this.actionManager.dispose();
  13684. this.actionManager = null;
  13685. }
  13686. // Skeleton
  13687. this.skeleton = null;
  13688. // Animations
  13689. this.getScene().stopAnimation(this);
  13690. // Physics
  13691. if (this.physicsImpostor) {
  13692. this.physicsImpostor.dispose();
  13693. }
  13694. // Intersections in progress
  13695. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13696. var other = this._intersectionsInProgress[index];
  13697. var pos = other._intersectionsInProgress.indexOf(this);
  13698. other._intersectionsInProgress.splice(pos, 1);
  13699. }
  13700. this._intersectionsInProgress = [];
  13701. // Lights
  13702. var lights = this.getScene().lights;
  13703. lights.forEach(function (light) {
  13704. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13705. if (meshIndex !== -1) {
  13706. light.includedOnlyMeshes.splice(meshIndex, 1);
  13707. }
  13708. meshIndex = light.excludedMeshes.indexOf(_this);
  13709. if (meshIndex !== -1) {
  13710. light.excludedMeshes.splice(meshIndex, 1);
  13711. }
  13712. // Shadow generators
  13713. var generator = light.getShadowGenerator();
  13714. if (generator) {
  13715. var shadowMap = generator.getShadowMap();
  13716. meshIndex = shadowMap.renderList.indexOf(_this);
  13717. if (meshIndex !== -1) {
  13718. shadowMap.renderList.splice(meshIndex, 1);
  13719. }
  13720. }
  13721. });
  13722. // Edges
  13723. if (this._edgesRenderer) {
  13724. this._edgesRenderer.dispose();
  13725. this._edgesRenderer = null;
  13726. }
  13727. // SubMeshes
  13728. if (this.getClassName() !== "InstancedMesh") {
  13729. this.releaseSubMeshes();
  13730. }
  13731. // Octree
  13732. var sceneOctree = this.getScene().selectionOctree;
  13733. if (sceneOctree) {
  13734. var index = sceneOctree.dynamicContent.indexOf(this);
  13735. if (index !== -1) {
  13736. sceneOctree.dynamicContent.splice(index, 1);
  13737. }
  13738. }
  13739. // Query
  13740. var engine = this.getScene().getEngine();
  13741. if (this._occlusionQuery) {
  13742. this._isOcclusionQueryInProgress = false;
  13743. engine.deleteQuery(this._occlusionQuery);
  13744. this._occlusionQuery = null;
  13745. }
  13746. // Engine
  13747. engine.wipeCaches();
  13748. // Remove from scene
  13749. this.getScene().removeMesh(this);
  13750. if (!doNotRecurse) {
  13751. // Particles
  13752. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13753. if (this.getScene().particleSystems[index].emitter === this) {
  13754. this.getScene().particleSystems[index].dispose();
  13755. index--;
  13756. }
  13757. }
  13758. // Children
  13759. var objects = this.getDescendants(true);
  13760. for (index = 0; index < objects.length; index++) {
  13761. objects[index].dispose();
  13762. }
  13763. }
  13764. else {
  13765. var childMeshes = this.getChildMeshes(true);
  13766. for (index = 0; index < childMeshes.length; index++) {
  13767. var child = childMeshes[index];
  13768. child.parent = null;
  13769. child.computeWorldMatrix(true);
  13770. }
  13771. }
  13772. // facet data
  13773. if (this._facetDataEnabled) {
  13774. this.disableFacetData();
  13775. }
  13776. this.onAfterWorldMatrixUpdateObservable.clear();
  13777. this.onCollideObservable.clear();
  13778. this.onCollisionPositionChangeObservable.clear();
  13779. this._isDisposed = true;
  13780. _super.prototype.dispose.call(this);
  13781. };
  13782. /**
  13783. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13784. * This Vector3 is expressed in the World space.
  13785. */
  13786. AbstractMesh.prototype.getDirection = function (localAxis) {
  13787. var result = BABYLON.Vector3.Zero();
  13788. this.getDirectionToRef(localAxis, result);
  13789. return result;
  13790. };
  13791. /**
  13792. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13793. * localAxis is expressed in the mesh local space.
  13794. * result is computed in the Wordl space from the mesh World matrix.
  13795. * Returns the AbstractMesh.
  13796. */
  13797. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13798. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13799. return this;
  13800. };
  13801. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13802. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13803. if (this.getScene().getRenderId() == 0) {
  13804. this.computeWorldMatrix(true);
  13805. }
  13806. var wm = this.getWorldMatrix();
  13807. if (space == BABYLON.Space.WORLD) {
  13808. var tmat = BABYLON.Tmp.Matrix[0];
  13809. wm.invertToRef(tmat);
  13810. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13811. }
  13812. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13813. this._pivotMatrix.m[12] = -point.x;
  13814. this._pivotMatrix.m[13] = -point.y;
  13815. this._pivotMatrix.m[14] = -point.z;
  13816. this._cache.pivotMatrixUpdated = true;
  13817. return this;
  13818. };
  13819. /**
  13820. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13821. */
  13822. AbstractMesh.prototype.getPivotPoint = function () {
  13823. var point = BABYLON.Vector3.Zero();
  13824. this.getPivotPointToRef(point);
  13825. return point;
  13826. };
  13827. /**
  13828. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13829. * Returns the AbstractMesh.
  13830. */
  13831. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13832. result.x = -this._pivotMatrix.m[12];
  13833. result.y = -this._pivotMatrix.m[13];
  13834. result.z = -this._pivotMatrix.m[14];
  13835. return this;
  13836. };
  13837. /**
  13838. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13839. */
  13840. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13841. var point = BABYLON.Vector3.Zero();
  13842. this.getAbsolutePivotPointToRef(point);
  13843. return point;
  13844. };
  13845. /**
  13846. * Defines the passed mesh as the parent of the current mesh.
  13847. * Returns the AbstractMesh.
  13848. */
  13849. AbstractMesh.prototype.setParent = function (mesh) {
  13850. var child = this;
  13851. var parent = mesh;
  13852. if (mesh == null) {
  13853. var rotation = BABYLON.Tmp.Quaternion[0];
  13854. var position = BABYLON.Tmp.Vector3[0];
  13855. var scale = BABYLON.Tmp.Vector3[1];
  13856. child.getWorldMatrix().decompose(scale, rotation, position);
  13857. if (child.rotationQuaternion) {
  13858. child.rotationQuaternion.copyFrom(rotation);
  13859. }
  13860. else {
  13861. rotation.toEulerAnglesToRef(child.rotation);
  13862. }
  13863. child.position.x = position.x;
  13864. child.position.y = position.y;
  13865. child.position.z = position.z;
  13866. }
  13867. else {
  13868. var rotation = BABYLON.Tmp.Quaternion[0];
  13869. var position = BABYLON.Tmp.Vector3[0];
  13870. var scale = BABYLON.Tmp.Vector3[1];
  13871. var m1 = BABYLON.Tmp.Matrix[0];
  13872. var m2 = BABYLON.Tmp.Matrix[1];
  13873. parent.getWorldMatrix().decompose(scale, rotation, position);
  13874. rotation.toRotationMatrix(m1);
  13875. m2.setTranslation(position);
  13876. m2.multiplyToRef(m1, m1);
  13877. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13878. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13879. m.decompose(scale, rotation, position);
  13880. if (child.rotationQuaternion) {
  13881. child.rotationQuaternion.copyFrom(rotation);
  13882. }
  13883. else {
  13884. rotation.toEulerAnglesToRef(child.rotation);
  13885. }
  13886. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13887. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13888. m.decompose(scale, rotation, position);
  13889. child.position.x = position.x;
  13890. child.position.y = position.y;
  13891. child.position.z = position.z;
  13892. }
  13893. child.parent = parent;
  13894. return this;
  13895. };
  13896. /**
  13897. * Adds the passed mesh as a child to the current mesh.
  13898. * Returns the AbstractMesh.
  13899. */
  13900. AbstractMesh.prototype.addChild = function (mesh) {
  13901. mesh.setParent(this);
  13902. return this;
  13903. };
  13904. /**
  13905. * Removes the passed mesh from the current mesh children list.
  13906. * Returns the AbstractMesh.
  13907. */
  13908. AbstractMesh.prototype.removeChild = function (mesh) {
  13909. mesh.setParent(null);
  13910. return this;
  13911. };
  13912. /**
  13913. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13914. * Returns the AbstractMesh.
  13915. */
  13916. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13917. result.x = this._pivotMatrix.m[12];
  13918. result.y = this._pivotMatrix.m[13];
  13919. result.z = this._pivotMatrix.m[14];
  13920. this.getPivotPointToRef(result);
  13921. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13922. return this;
  13923. };
  13924. // Facet data
  13925. /**
  13926. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13927. * Returns the AbstractMesh.
  13928. */
  13929. AbstractMesh.prototype._initFacetData = function () {
  13930. if (!this._facetNormals) {
  13931. this._facetNormals = new Array();
  13932. }
  13933. if (!this._facetPositions) {
  13934. this._facetPositions = new Array();
  13935. }
  13936. if (!this._facetPartitioning) {
  13937. this._facetPartitioning = new Array();
  13938. }
  13939. this._facetNb = this.getIndices().length / 3;
  13940. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13941. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13942. for (var f = 0; f < this._facetNb; f++) {
  13943. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13944. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13945. }
  13946. this._facetDataEnabled = true;
  13947. return this;
  13948. };
  13949. /**
  13950. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13951. * This method can be called within the render loop.
  13952. * 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.
  13953. * Returns the AbstractMesh.
  13954. */
  13955. AbstractMesh.prototype.updateFacetData = function () {
  13956. if (!this._facetDataEnabled) {
  13957. this._initFacetData();
  13958. }
  13959. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13960. var indices = this.getIndices();
  13961. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13962. var bInfo = this.getBoundingInfo();
  13963. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13964. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13965. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13966. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13967. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13968. this._subDiv.max = this._partitioningSubdivisions;
  13969. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13970. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13971. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13972. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13973. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13974. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13975. // set the parameters for ComputeNormals()
  13976. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13977. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13978. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13979. this._facetParameters.bInfo = bInfo;
  13980. this._facetParameters.bbSize = this._bbSize;
  13981. this._facetParameters.subDiv = this._subDiv;
  13982. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13983. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13984. return this;
  13985. };
  13986. /**
  13987. * Returns the facetLocalNormals array.
  13988. * The normals are expressed in the mesh local space.
  13989. */
  13990. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13991. if (!this._facetNormals) {
  13992. this.updateFacetData();
  13993. }
  13994. return this._facetNormals;
  13995. };
  13996. /**
  13997. * Returns the facetLocalPositions array.
  13998. * The facet positions are expressed in the mesh local space.
  13999. */
  14000. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14001. if (!this._facetPositions) {
  14002. this.updateFacetData();
  14003. }
  14004. return this._facetPositions;
  14005. };
  14006. /**
  14007. * Returns the facetLocalPartioning array.
  14008. */
  14009. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14010. if (!this._facetPartitioning) {
  14011. this.updateFacetData();
  14012. }
  14013. return this._facetPartitioning;
  14014. };
  14015. /**
  14016. * Returns the i-th facet position in the world system.
  14017. * This method allocates a new Vector3 per call.
  14018. */
  14019. AbstractMesh.prototype.getFacetPosition = function (i) {
  14020. var pos = BABYLON.Vector3.Zero();
  14021. this.getFacetPositionToRef(i, pos);
  14022. return pos;
  14023. };
  14024. /**
  14025. * Sets the reference Vector3 with the i-th facet position in the world system.
  14026. * Returns the AbstractMesh.
  14027. */
  14028. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14029. var localPos = (this.getFacetLocalPositions())[i];
  14030. var world = this.getWorldMatrix();
  14031. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14032. return this;
  14033. };
  14034. /**
  14035. * Returns the i-th facet normal in the world system.
  14036. * This method allocates a new Vector3 per call.
  14037. */
  14038. AbstractMesh.prototype.getFacetNormal = function (i) {
  14039. var norm = BABYLON.Vector3.Zero();
  14040. this.getFacetNormalToRef(i, norm);
  14041. return norm;
  14042. };
  14043. /**
  14044. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14045. * Returns the AbstractMesh.
  14046. */
  14047. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14048. var localNorm = (this.getFacetLocalNormals())[i];
  14049. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14050. return this;
  14051. };
  14052. /**
  14053. * 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).
  14054. */
  14055. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14056. var bInfo = this.getBoundingInfo();
  14057. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14058. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14059. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14060. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14061. return null;
  14062. }
  14063. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14064. };
  14065. /**
  14066. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14067. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14068. * 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.
  14069. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14070. * 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.
  14071. */
  14072. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14073. if (checkFace === void 0) { checkFace = false; }
  14074. if (facing === void 0) { facing = true; }
  14075. var world = this.getWorldMatrix();
  14076. var invMat = BABYLON.Tmp.Matrix[5];
  14077. world.invertToRef(invMat);
  14078. var invVect = BABYLON.Tmp.Vector3[8];
  14079. var closest = null;
  14080. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14081. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14082. if (projected) {
  14083. // tranform the local computed projected vector to world coordinates
  14084. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14085. }
  14086. return closest;
  14087. };
  14088. /**
  14089. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14090. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14091. * 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.
  14092. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14093. * 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.
  14094. */
  14095. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14096. if (checkFace === void 0) { checkFace = false; }
  14097. if (facing === void 0) { facing = true; }
  14098. var closest = null;
  14099. var tmpx = 0.0;
  14100. var tmpy = 0.0;
  14101. var tmpz = 0.0;
  14102. var d = 0.0; // tmp dot facet normal * facet position
  14103. var t0 = 0.0;
  14104. var projx = 0.0;
  14105. var projy = 0.0;
  14106. var projz = 0.0;
  14107. // Get all the facets in the same partitioning block than (x, y, z)
  14108. var facetPositions = this.getFacetLocalPositions();
  14109. var facetNormals = this.getFacetLocalNormals();
  14110. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14111. if (!facetsInBlock) {
  14112. return null;
  14113. }
  14114. // Get the closest facet to (x, y, z)
  14115. var shortest = Number.MAX_VALUE; // init distance vars
  14116. var tmpDistance = shortest;
  14117. var fib; // current facet in the block
  14118. var norm; // current facet normal
  14119. var p0; // current facet barycenter position
  14120. // loop on all the facets in the current partitioning block
  14121. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14122. fib = facetsInBlock[idx];
  14123. norm = facetNormals[fib];
  14124. p0 = facetPositions[fib];
  14125. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14126. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14127. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14128. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14129. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14130. projx = x + norm.x * t0;
  14131. projy = y + norm.y * t0;
  14132. projz = z + norm.z * t0;
  14133. tmpx = projx - x;
  14134. tmpy = projy - y;
  14135. tmpz = projz - z;
  14136. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14137. if (tmpDistance < shortest) {
  14138. shortest = tmpDistance;
  14139. closest = fib;
  14140. if (projected) {
  14141. projected.x = projx;
  14142. projected.y = projy;
  14143. projected.z = projz;
  14144. }
  14145. }
  14146. }
  14147. }
  14148. return closest;
  14149. };
  14150. /**
  14151. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14152. */
  14153. AbstractMesh.prototype.getFacetDataParameters = function () {
  14154. return this._facetParameters;
  14155. };
  14156. /**
  14157. * Disables the feature FacetData and frees the related memory.
  14158. * Returns the AbstractMesh.
  14159. */
  14160. AbstractMesh.prototype.disableFacetData = function () {
  14161. if (this._facetDataEnabled) {
  14162. this._facetDataEnabled = false;
  14163. this._facetPositions = null;
  14164. this._facetNormals = null;
  14165. this._facetPartitioning = null;
  14166. this._facetParameters = null;
  14167. }
  14168. return this;
  14169. };
  14170. /**
  14171. * Creates new normals data for the mesh.
  14172. * @param updatable.
  14173. */
  14174. AbstractMesh.prototype.createNormals = function (updatable) {
  14175. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14176. var indices = this.getIndices();
  14177. var normals;
  14178. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14179. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14180. }
  14181. else {
  14182. normals = [];
  14183. }
  14184. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14185. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14186. };
  14187. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14188. var engine = this.getEngine();
  14189. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14190. this._isOccluded = false;
  14191. return;
  14192. }
  14193. if (this.isOcclusionQueryInProgress) {
  14194. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14195. if (isOcclusionQueryAvailable) {
  14196. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14197. this._isOcclusionQueryInProgress = false;
  14198. this._occlusionInternalRetryCounter = 0;
  14199. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14200. }
  14201. else {
  14202. this._occlusionInternalRetryCounter++;
  14203. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14204. this._isOcclusionQueryInProgress = false;
  14205. this._occlusionInternalRetryCounter = 0;
  14206. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14207. // if strict continue the last state of the object.
  14208. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14209. }
  14210. else {
  14211. return;
  14212. }
  14213. }
  14214. }
  14215. var scene = this.getScene();
  14216. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14217. if (!this._occlusionQuery) {
  14218. this._occlusionQuery = engine.createQuery();
  14219. }
  14220. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14221. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14222. engine.endQuery(this.occlusionQueryAlgorithmType);
  14223. this._isOcclusionQueryInProgress = true;
  14224. };
  14225. // Statics
  14226. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14227. AbstractMesh._BILLBOARDMODE_X = 1;
  14228. AbstractMesh._BILLBOARDMODE_Y = 2;
  14229. AbstractMesh._BILLBOARDMODE_Z = 4;
  14230. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14231. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14232. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14233. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14234. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14235. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14236. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14237. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14238. return AbstractMesh;
  14239. }(BABYLON.Node));
  14240. BABYLON.AbstractMesh = AbstractMesh;
  14241. })(BABYLON || (BABYLON = {}));
  14242. //# sourceMappingURL=babylon.abstractMesh.js.map
  14243. var BABYLON;
  14244. (function (BABYLON) {
  14245. var Light = (function (_super) {
  14246. __extends(Light, _super);
  14247. /**
  14248. * Creates a Light object in the scene.
  14249. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14250. */
  14251. function Light(name, scene) {
  14252. var _this = _super.call(this, name, scene) || this;
  14253. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14254. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14255. _this.intensity = 1.0;
  14256. _this.range = Number.MAX_VALUE;
  14257. /**
  14258. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14259. * of light.
  14260. */
  14261. _this._photometricScale = 1.0;
  14262. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14263. _this._radius = 0.00001;
  14264. _this.renderPriority = 0;
  14265. /**
  14266. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14267. * the current shadow generator.
  14268. */
  14269. _this.shadowEnabled = true;
  14270. _this._excludeWithLayerMask = 0;
  14271. _this._includeOnlyWithLayerMask = 0;
  14272. _this._lightmapMode = 0;
  14273. _this._excludedMeshesIds = new Array();
  14274. _this._includedOnlyMeshesIds = new Array();
  14275. _this.getScene().addLight(_this);
  14276. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14277. _this._buildUniformLayout();
  14278. _this.includedOnlyMeshes = new Array();
  14279. _this.excludedMeshes = new Array();
  14280. _this._resyncMeshes();
  14281. return _this;
  14282. }
  14283. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14284. /**
  14285. * If every light affecting the material is in this lightmapMode,
  14286. * material.lightmapTexture adds or multiplies
  14287. * (depends on material.useLightmapAsShadowmap)
  14288. * after every other light calculations.
  14289. */
  14290. get: function () {
  14291. return Light._LIGHTMAP_DEFAULT;
  14292. },
  14293. enumerable: true,
  14294. configurable: true
  14295. });
  14296. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14297. /**
  14298. * material.lightmapTexture as only diffuse lighting from this light
  14299. * adds pnly specular lighting from this light
  14300. * adds dynamic shadows
  14301. */
  14302. get: function () {
  14303. return Light._LIGHTMAP_SPECULAR;
  14304. },
  14305. enumerable: true,
  14306. configurable: true
  14307. });
  14308. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14309. /**
  14310. * material.lightmapTexture as only lighting
  14311. * no light calculation from this light
  14312. * only adds dynamic shadows from this light
  14313. */
  14314. get: function () {
  14315. return Light._LIGHTMAP_SHADOWSONLY;
  14316. },
  14317. enumerable: true,
  14318. configurable: true
  14319. });
  14320. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14321. /**
  14322. * Each light type uses the default quantity according to its type:
  14323. * point/spot lights use luminous intensity
  14324. * directional lights use illuminance
  14325. */
  14326. get: function () {
  14327. return Light._INTENSITYMODE_AUTOMATIC;
  14328. },
  14329. enumerable: true,
  14330. configurable: true
  14331. });
  14332. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14333. /**
  14334. * lumen (lm)
  14335. */
  14336. get: function () {
  14337. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14338. },
  14339. enumerable: true,
  14340. configurable: true
  14341. });
  14342. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14343. /**
  14344. * candela (lm/sr)
  14345. */
  14346. get: function () {
  14347. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14348. },
  14349. enumerable: true,
  14350. configurable: true
  14351. });
  14352. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14353. /**
  14354. * lux (lm/m^2)
  14355. */
  14356. get: function () {
  14357. return Light._INTENSITYMODE_ILLUMINANCE;
  14358. },
  14359. enumerable: true,
  14360. configurable: true
  14361. });
  14362. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14363. /**
  14364. * nit (cd/m^2)
  14365. */
  14366. get: function () {
  14367. return Light._INTENSITYMODE_LUMINANCE;
  14368. },
  14369. enumerable: true,
  14370. configurable: true
  14371. });
  14372. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14373. /**
  14374. * Light type const id of the point light.
  14375. */
  14376. get: function () {
  14377. return Light._LIGHTTYPEID_POINTLIGHT;
  14378. },
  14379. enumerable: true,
  14380. configurable: true
  14381. });
  14382. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14383. /**
  14384. * Light type const id of the directional light.
  14385. */
  14386. get: function () {
  14387. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14388. },
  14389. enumerable: true,
  14390. configurable: true
  14391. });
  14392. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14393. /**
  14394. * Light type const id of the spot light.
  14395. */
  14396. get: function () {
  14397. return Light._LIGHTTYPEID_SPOTLIGHT;
  14398. },
  14399. enumerable: true,
  14400. configurable: true
  14401. });
  14402. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14403. /**
  14404. * Light type const id of the hemispheric light.
  14405. */
  14406. get: function () {
  14407. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14408. },
  14409. enumerable: true,
  14410. configurable: true
  14411. });
  14412. Object.defineProperty(Light.prototype, "intensityMode", {
  14413. /**
  14414. * Gets the photometric scale used to interpret the intensity.
  14415. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14416. */
  14417. get: function () {
  14418. return this._intensityMode;
  14419. },
  14420. /**
  14421. * Sets the photometric scale used to interpret the intensity.
  14422. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14423. */
  14424. set: function (value) {
  14425. this._intensityMode = value;
  14426. this._computePhotometricScale();
  14427. },
  14428. enumerable: true,
  14429. configurable: true
  14430. });
  14431. ;
  14432. ;
  14433. Object.defineProperty(Light.prototype, "radius", {
  14434. /**
  14435. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14436. */
  14437. get: function () {
  14438. return this._radius;
  14439. },
  14440. /**
  14441. * sets the light radius used by PBR Materials to simulate soft area lights.
  14442. */
  14443. set: function (value) {
  14444. this._radius = value;
  14445. this._computePhotometricScale();
  14446. },
  14447. enumerable: true,
  14448. configurable: true
  14449. });
  14450. ;
  14451. ;
  14452. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14453. get: function () {
  14454. return this._includedOnlyMeshes;
  14455. },
  14456. set: function (value) {
  14457. this._includedOnlyMeshes = value;
  14458. this._hookArrayForIncludedOnly(value);
  14459. },
  14460. enumerable: true,
  14461. configurable: true
  14462. });
  14463. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14464. get: function () {
  14465. return this._excludedMeshes;
  14466. },
  14467. set: function (value) {
  14468. this._excludedMeshes = value;
  14469. this._hookArrayForExcluded(value);
  14470. },
  14471. enumerable: true,
  14472. configurable: true
  14473. });
  14474. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14475. get: function () {
  14476. return this._excludeWithLayerMask;
  14477. },
  14478. set: function (value) {
  14479. this._excludeWithLayerMask = value;
  14480. this._resyncMeshes();
  14481. },
  14482. enumerable: true,
  14483. configurable: true
  14484. });
  14485. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14486. get: function () {
  14487. return this._includeOnlyWithLayerMask;
  14488. },
  14489. set: function (value) {
  14490. this._includeOnlyWithLayerMask = value;
  14491. this._resyncMeshes();
  14492. },
  14493. enumerable: true,
  14494. configurable: true
  14495. });
  14496. Object.defineProperty(Light.prototype, "lightmapMode", {
  14497. get: function () {
  14498. return this._lightmapMode;
  14499. },
  14500. set: function (value) {
  14501. if (this._lightmapMode === value) {
  14502. return;
  14503. }
  14504. this._lightmapMode = value;
  14505. this._markMeshesAsLightDirty();
  14506. },
  14507. enumerable: true,
  14508. configurable: true
  14509. });
  14510. Light.prototype._buildUniformLayout = function () {
  14511. // Overridden
  14512. };
  14513. /**
  14514. * Returns the string "Light".
  14515. */
  14516. Light.prototype.getClassName = function () {
  14517. return "Light";
  14518. };
  14519. /**
  14520. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14521. */
  14522. Light.prototype.toString = function (fullDetails) {
  14523. var ret = "Name: " + this.name;
  14524. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14525. if (this.animations) {
  14526. for (var i = 0; i < this.animations.length; i++) {
  14527. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14528. }
  14529. }
  14530. if (fullDetails) {
  14531. }
  14532. return ret;
  14533. };
  14534. /**
  14535. * Set the enabled state of this node.
  14536. * @param {boolean} value - the new enabled state
  14537. * @see isEnabled
  14538. */
  14539. Light.prototype.setEnabled = function (value) {
  14540. _super.prototype.setEnabled.call(this, value);
  14541. this._resyncMeshes();
  14542. };
  14543. /**
  14544. * Returns the Light associated shadow generator.
  14545. */
  14546. Light.prototype.getShadowGenerator = function () {
  14547. return this._shadowGenerator;
  14548. };
  14549. /**
  14550. * Returns a Vector3, the absolute light position in the World.
  14551. */
  14552. Light.prototype.getAbsolutePosition = function () {
  14553. return BABYLON.Vector3.Zero();
  14554. };
  14555. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14556. };
  14557. Light.prototype._getWorldMatrix = function () {
  14558. return BABYLON.Matrix.Identity();
  14559. };
  14560. /**
  14561. * Boolean : True if the light will affect the passed mesh.
  14562. */
  14563. Light.prototype.canAffectMesh = function (mesh) {
  14564. if (!mesh) {
  14565. return true;
  14566. }
  14567. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14568. return false;
  14569. }
  14570. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14571. return false;
  14572. }
  14573. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14574. return false;
  14575. }
  14576. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14577. return false;
  14578. }
  14579. return true;
  14580. };
  14581. /**
  14582. * Returns the light World matrix.
  14583. */
  14584. Light.prototype.getWorldMatrix = function () {
  14585. this._currentRenderId = this.getScene().getRenderId();
  14586. var worldMatrix = this._getWorldMatrix();
  14587. if (this.parent && this.parent.getWorldMatrix) {
  14588. if (!this._parentedWorldMatrix) {
  14589. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14590. }
  14591. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14592. this._markSyncedWithParent();
  14593. return this._parentedWorldMatrix;
  14594. }
  14595. return worldMatrix;
  14596. };
  14597. /**
  14598. * Sort function to order lights for rendering.
  14599. * @param a First Light object to compare to second.
  14600. * @param b Second Light object to compare first.
  14601. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14602. */
  14603. Light.compareLightsPriority = function (a, b) {
  14604. //shadow-casting lights have priority over non-shadow-casting lights
  14605. //the renderPrioirty is a secondary sort criterion
  14606. if (a.shadowEnabled !== b.shadowEnabled) {
  14607. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14608. }
  14609. return b.renderPriority - a.renderPriority;
  14610. };
  14611. /**
  14612. * Disposes the light.
  14613. */
  14614. Light.prototype.dispose = function () {
  14615. if (this._shadowGenerator) {
  14616. this._shadowGenerator.dispose();
  14617. this._shadowGenerator = null;
  14618. }
  14619. // Animations
  14620. this.getScene().stopAnimation(this);
  14621. // Remove from meshes
  14622. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14623. var mesh = _a[_i];
  14624. mesh._removeLightSource(this);
  14625. }
  14626. this._uniformBuffer.dispose();
  14627. // Remove from scene
  14628. this.getScene().removeLight(this);
  14629. _super.prototype.dispose.call(this);
  14630. };
  14631. /**
  14632. * Returns the light type ID (integer).
  14633. */
  14634. Light.prototype.getTypeID = function () {
  14635. return 0;
  14636. };
  14637. /**
  14638. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14639. */
  14640. Light.prototype.getScaledIntensity = function () {
  14641. return this._photometricScale * this.intensity;
  14642. };
  14643. /**
  14644. * Returns a new Light object, named "name", from the current one.
  14645. */
  14646. Light.prototype.clone = function (name) {
  14647. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14648. };
  14649. /**
  14650. * Serializes the current light into a Serialization object.
  14651. * Returns the serialized object.
  14652. */
  14653. Light.prototype.serialize = function () {
  14654. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14655. // Type
  14656. serializationObject.type = this.getTypeID();
  14657. // Parent
  14658. if (this.parent) {
  14659. serializationObject.parentId = this.parent.id;
  14660. }
  14661. // Inclusion / exclusions
  14662. if (this.excludedMeshes.length > 0) {
  14663. serializationObject.excludedMeshesIds = [];
  14664. this.excludedMeshes.forEach(function (mesh) {
  14665. serializationObject.excludedMeshesIds.push(mesh.id);
  14666. });
  14667. }
  14668. if (this.includedOnlyMeshes.length > 0) {
  14669. serializationObject.includedOnlyMeshesIds = [];
  14670. this.includedOnlyMeshes.forEach(function (mesh) {
  14671. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14672. });
  14673. }
  14674. // Animations
  14675. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14676. serializationObject.ranges = this.serializeAnimationRanges();
  14677. return serializationObject;
  14678. };
  14679. /**
  14680. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14681. * This new light is named "name" and added to the passed scene.
  14682. */
  14683. Light.GetConstructorFromName = function (type, name, scene) {
  14684. switch (type) {
  14685. case 0:
  14686. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14687. case 1:
  14688. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14689. case 2:
  14690. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14691. case 3:
  14692. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14693. }
  14694. };
  14695. /**
  14696. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14697. */
  14698. Light.Parse = function (parsedLight, scene) {
  14699. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14700. // Inclusion / exclusions
  14701. if (parsedLight.excludedMeshesIds) {
  14702. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14703. }
  14704. if (parsedLight.includedOnlyMeshesIds) {
  14705. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14706. }
  14707. // Parent
  14708. if (parsedLight.parentId) {
  14709. light._waitingParentId = parsedLight.parentId;
  14710. }
  14711. // Animations
  14712. if (parsedLight.animations) {
  14713. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14714. var parsedAnimation = parsedLight.animations[animationIndex];
  14715. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14716. }
  14717. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14718. }
  14719. if (parsedLight.autoAnimate) {
  14720. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14721. }
  14722. return light;
  14723. };
  14724. Light.prototype._hookArrayForExcluded = function (array) {
  14725. var _this = this;
  14726. var oldPush = array.push;
  14727. array.push = function () {
  14728. var items = [];
  14729. for (var _i = 0; _i < arguments.length; _i++) {
  14730. items[_i] = arguments[_i];
  14731. }
  14732. var result = oldPush.apply(array, items);
  14733. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14734. var item = items_1[_a];
  14735. item._resyncLighSource(_this);
  14736. }
  14737. return result;
  14738. };
  14739. var oldSplice = array.splice;
  14740. array.splice = function (index, deleteCount) {
  14741. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14742. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14743. var item = deleted_1[_i];
  14744. item._resyncLighSource(_this);
  14745. }
  14746. return deleted;
  14747. };
  14748. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14749. var item = array_1[_i];
  14750. item._resyncLighSource(this);
  14751. }
  14752. };
  14753. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14754. var _this = this;
  14755. var oldPush = array.push;
  14756. array.push = function () {
  14757. var items = [];
  14758. for (var _i = 0; _i < arguments.length; _i++) {
  14759. items[_i] = arguments[_i];
  14760. }
  14761. var result = oldPush.apply(array, items);
  14762. _this._resyncMeshes();
  14763. return result;
  14764. };
  14765. var oldSplice = array.splice;
  14766. array.splice = function (index, deleteCount) {
  14767. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14768. _this._resyncMeshes();
  14769. return deleted;
  14770. };
  14771. this._resyncMeshes();
  14772. };
  14773. Light.prototype._resyncMeshes = function () {
  14774. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14775. var mesh = _a[_i];
  14776. mesh._resyncLighSource(this);
  14777. }
  14778. };
  14779. Light.prototype._markMeshesAsLightDirty = function () {
  14780. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14781. var mesh = _a[_i];
  14782. if (mesh._lightSources.indexOf(this) !== -1) {
  14783. mesh._markSubMeshesAsLightDirty();
  14784. }
  14785. }
  14786. };
  14787. /**
  14788. * Recomputes the cached photometric scale if needed.
  14789. */
  14790. Light.prototype._computePhotometricScale = function () {
  14791. this._photometricScale = this._getPhotometricScale();
  14792. this.getScene().resetCachedMaterial();
  14793. };
  14794. /**
  14795. * Returns the Photometric Scale according to the light type and intensity mode.
  14796. */
  14797. Light.prototype._getPhotometricScale = function () {
  14798. var photometricScale = 0.0;
  14799. var lightTypeID = this.getTypeID();
  14800. //get photometric mode
  14801. var photometricMode = this.intensityMode;
  14802. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14803. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14804. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14805. }
  14806. else {
  14807. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14808. }
  14809. }
  14810. //compute photometric scale
  14811. switch (lightTypeID) {
  14812. case Light.LIGHTTYPEID_POINTLIGHT:
  14813. case Light.LIGHTTYPEID_SPOTLIGHT:
  14814. switch (photometricMode) {
  14815. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14816. photometricScale = 1.0 / (4.0 * Math.PI);
  14817. break;
  14818. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14819. photometricScale = 1.0;
  14820. break;
  14821. case Light.INTENSITYMODE_LUMINANCE:
  14822. photometricScale = this.radius * this.radius;
  14823. break;
  14824. }
  14825. break;
  14826. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14827. switch (photometricMode) {
  14828. case Light.INTENSITYMODE_ILLUMINANCE:
  14829. photometricScale = 1.0;
  14830. break;
  14831. case Light.INTENSITYMODE_LUMINANCE:
  14832. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14833. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14834. var apexAngleRadians = this.radius;
  14835. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14836. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14837. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14838. photometricScale = solidAngle;
  14839. break;
  14840. }
  14841. break;
  14842. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14843. // No fall off in hemisperic light.
  14844. photometricScale = 1.0;
  14845. break;
  14846. }
  14847. return photometricScale;
  14848. };
  14849. Light.prototype._reorderLightsInScene = function () {
  14850. var scene = this.getScene();
  14851. if (this.renderPriority != 0) {
  14852. scene.requireLightSorting = true;
  14853. }
  14854. this.getScene().sortLightsByPriority();
  14855. };
  14856. //lightmapMode Consts
  14857. Light._LIGHTMAP_DEFAULT = 0;
  14858. Light._LIGHTMAP_SPECULAR = 1;
  14859. Light._LIGHTMAP_SHADOWSONLY = 2;
  14860. // Intensity Mode Consts
  14861. Light._INTENSITYMODE_AUTOMATIC = 0;
  14862. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14863. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14864. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14865. Light._INTENSITYMODE_LUMINANCE = 4;
  14866. // Light types ids const.
  14867. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14868. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14869. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14870. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14871. __decorate([
  14872. BABYLON.serializeAsColor3()
  14873. ], Light.prototype, "diffuse", void 0);
  14874. __decorate([
  14875. BABYLON.serializeAsColor3()
  14876. ], Light.prototype, "specular", void 0);
  14877. __decorate([
  14878. BABYLON.serialize()
  14879. ], Light.prototype, "intensity", void 0);
  14880. __decorate([
  14881. BABYLON.serialize()
  14882. ], Light.prototype, "range", void 0);
  14883. __decorate([
  14884. BABYLON.serialize()
  14885. ], Light.prototype, "intensityMode", null);
  14886. __decorate([
  14887. BABYLON.serialize()
  14888. ], Light.prototype, "radius", null);
  14889. __decorate([
  14890. BABYLON.serialize()
  14891. ], Light.prototype, "_renderPriority", void 0);
  14892. __decorate([
  14893. BABYLON.expandToProperty("_reorderLightsInScene")
  14894. ], Light.prototype, "renderPriority", void 0);
  14895. __decorate([
  14896. BABYLON.serialize()
  14897. ], Light.prototype, "shadowEnabled", void 0);
  14898. __decorate([
  14899. BABYLON.serialize("excludeWithLayerMask")
  14900. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14901. __decorate([
  14902. BABYLON.serialize("includeOnlyWithLayerMask")
  14903. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14904. __decorate([
  14905. BABYLON.serialize("lightmapMode")
  14906. ], Light.prototype, "_lightmapMode", void 0);
  14907. return Light;
  14908. }(BABYLON.Node));
  14909. BABYLON.Light = Light;
  14910. })(BABYLON || (BABYLON = {}));
  14911. //# sourceMappingURL=babylon.light.js.map
  14912. var BABYLON;
  14913. (function (BABYLON) {
  14914. var Camera = (function (_super) {
  14915. __extends(Camera, _super);
  14916. function Camera(name, position, scene) {
  14917. var _this = _super.call(this, name, scene) || this;
  14918. _this.upVector = BABYLON.Vector3.Up();
  14919. _this.orthoLeft = null;
  14920. _this.orthoRight = null;
  14921. _this.orthoBottom = null;
  14922. _this.orthoTop = null;
  14923. _this.fov = 0.8;
  14924. _this.minZ = 1;
  14925. _this.maxZ = 10000.0;
  14926. _this.inertia = 0.9;
  14927. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14928. _this.isIntermediate = false;
  14929. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14930. _this.layerMask = 0x0FFFFFFF;
  14931. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14932. // Camera rig members
  14933. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14934. _this._rigCameras = new Array();
  14935. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14936. _this.customRenderTargets = new Array();
  14937. // Observables
  14938. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14939. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14940. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  14941. // Cache
  14942. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14943. _this._projectionMatrix = new BABYLON.Matrix();
  14944. _this._doNotComputeProjectionMatrix = false;
  14945. _this._postProcesses = new Array();
  14946. _this._transformMatrix = BABYLON.Matrix.Zero();
  14947. _this._activeMeshes = new BABYLON.SmartArray(256);
  14948. _this._globalPosition = BABYLON.Vector3.Zero();
  14949. _this._refreshFrustumPlanes = true;
  14950. _this.getScene().addCamera(_this);
  14951. if (!_this.getScene().activeCamera) {
  14952. _this.getScene().activeCamera = _this;
  14953. }
  14954. _this.position = position;
  14955. return _this;
  14956. }
  14957. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  14958. get: function () {
  14959. return Camera._PERSPECTIVE_CAMERA;
  14960. },
  14961. enumerable: true,
  14962. configurable: true
  14963. });
  14964. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14965. get: function () {
  14966. return Camera._ORTHOGRAPHIC_CAMERA;
  14967. },
  14968. enumerable: true,
  14969. configurable: true
  14970. });
  14971. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14972. get: function () {
  14973. return Camera._FOVMODE_VERTICAL_FIXED;
  14974. },
  14975. enumerable: true,
  14976. configurable: true
  14977. });
  14978. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  14979. get: function () {
  14980. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14981. },
  14982. enumerable: true,
  14983. configurable: true
  14984. });
  14985. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14986. get: function () {
  14987. return Camera._RIG_MODE_NONE;
  14988. },
  14989. enumerable: true,
  14990. configurable: true
  14991. });
  14992. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14993. get: function () {
  14994. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14995. },
  14996. enumerable: true,
  14997. configurable: true
  14998. });
  14999. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15000. get: function () {
  15001. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15002. },
  15003. enumerable: true,
  15004. configurable: true
  15005. });
  15006. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15007. get: function () {
  15008. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15009. },
  15010. enumerable: true,
  15011. configurable: true
  15012. });
  15013. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15014. get: function () {
  15015. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15016. },
  15017. enumerable: true,
  15018. configurable: true
  15019. });
  15020. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15021. get: function () {
  15022. return Camera._RIG_MODE_VR;
  15023. },
  15024. enumerable: true,
  15025. configurable: true
  15026. });
  15027. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15028. get: function () {
  15029. return Camera._RIG_MODE_WEBVR;
  15030. },
  15031. enumerable: true,
  15032. configurable: true
  15033. });
  15034. /**
  15035. * Store current camera state (fov, position, etc..)
  15036. */
  15037. Camera.prototype.storeState = function () {
  15038. this._stateStored = true;
  15039. this._storedFov = this.fov;
  15040. return this;
  15041. };
  15042. /**
  15043. * Restored camera state. You must call storeState() first
  15044. */
  15045. Camera.prototype.restoreState = function () {
  15046. if (!this._stateStored) {
  15047. return false;
  15048. }
  15049. this.fov = this._storedFov;
  15050. return true;
  15051. };
  15052. Camera.prototype.getClassName = function () {
  15053. return "Camera";
  15054. };
  15055. /**
  15056. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15057. */
  15058. Camera.prototype.toString = function (fullDetails) {
  15059. var ret = "Name: " + this.name;
  15060. ret += ", type: " + this.getClassName();
  15061. if (this.animations) {
  15062. for (var i = 0; i < this.animations.length; i++) {
  15063. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15064. }
  15065. }
  15066. if (fullDetails) {
  15067. }
  15068. return ret;
  15069. };
  15070. Object.defineProperty(Camera.prototype, "globalPosition", {
  15071. get: function () {
  15072. return this._globalPosition;
  15073. },
  15074. enumerable: true,
  15075. configurable: true
  15076. });
  15077. Camera.prototype.getActiveMeshes = function () {
  15078. return this._activeMeshes;
  15079. };
  15080. Camera.prototype.isActiveMesh = function (mesh) {
  15081. return (this._activeMeshes.indexOf(mesh) !== -1);
  15082. };
  15083. //Cache
  15084. Camera.prototype._initCache = function () {
  15085. _super.prototype._initCache.call(this);
  15086. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15087. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15088. this._cache.mode = undefined;
  15089. this._cache.minZ = undefined;
  15090. this._cache.maxZ = undefined;
  15091. this._cache.fov = undefined;
  15092. this._cache.fovMode = undefined;
  15093. this._cache.aspectRatio = undefined;
  15094. this._cache.orthoLeft = undefined;
  15095. this._cache.orthoRight = undefined;
  15096. this._cache.orthoBottom = undefined;
  15097. this._cache.orthoTop = undefined;
  15098. this._cache.renderWidth = undefined;
  15099. this._cache.renderHeight = undefined;
  15100. };
  15101. Camera.prototype._updateCache = function (ignoreParentClass) {
  15102. if (!ignoreParentClass) {
  15103. _super.prototype._updateCache.call(this);
  15104. }
  15105. var engine = this.getEngine();
  15106. this._cache.position.copyFrom(this.position);
  15107. this._cache.upVector.copyFrom(this.upVector);
  15108. this._cache.mode = this.mode;
  15109. this._cache.minZ = this.minZ;
  15110. this._cache.maxZ = this.maxZ;
  15111. this._cache.fov = this.fov;
  15112. this._cache.fovMode = this.fovMode;
  15113. this._cache.aspectRatio = engine.getAspectRatio(this);
  15114. this._cache.orthoLeft = this.orthoLeft;
  15115. this._cache.orthoRight = this.orthoRight;
  15116. this._cache.orthoBottom = this.orthoBottom;
  15117. this._cache.orthoTop = this.orthoTop;
  15118. this._cache.renderWidth = engine.getRenderWidth();
  15119. this._cache.renderHeight = engine.getRenderHeight();
  15120. };
  15121. Camera.prototype._updateFromScene = function () {
  15122. this.updateCache();
  15123. this.update();
  15124. };
  15125. // Synchronized
  15126. Camera.prototype._isSynchronized = function () {
  15127. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15128. };
  15129. Camera.prototype._isSynchronizedViewMatrix = function () {
  15130. if (!_super.prototype._isSynchronized.call(this))
  15131. return false;
  15132. return this._cache.position.equals(this.position)
  15133. && this._cache.upVector.equals(this.upVector)
  15134. && this.isSynchronizedWithParent();
  15135. };
  15136. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15137. var check = this._cache.mode === this.mode
  15138. && this._cache.minZ === this.minZ
  15139. && this._cache.maxZ === this.maxZ;
  15140. if (!check) {
  15141. return false;
  15142. }
  15143. var engine = this.getEngine();
  15144. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15145. check = this._cache.fov === this.fov
  15146. && this._cache.fovMode === this.fovMode
  15147. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15148. }
  15149. else {
  15150. check = this._cache.orthoLeft === this.orthoLeft
  15151. && this._cache.orthoRight === this.orthoRight
  15152. && this._cache.orthoBottom === this.orthoBottom
  15153. && this._cache.orthoTop === this.orthoTop
  15154. && this._cache.renderWidth === engine.getRenderWidth()
  15155. && this._cache.renderHeight === engine.getRenderHeight();
  15156. }
  15157. return check;
  15158. };
  15159. // Controls
  15160. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15161. };
  15162. Camera.prototype.detachControl = function (element) {
  15163. };
  15164. Camera.prototype.update = function () {
  15165. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15166. this._updateRigCameras();
  15167. }
  15168. this._checkInputs();
  15169. };
  15170. Camera.prototype._checkInputs = function () {
  15171. this.onAfterCheckInputsObservable.notifyObservers(this);
  15172. };
  15173. Object.defineProperty(Camera.prototype, "rigCameras", {
  15174. get: function () {
  15175. return this._rigCameras;
  15176. },
  15177. enumerable: true,
  15178. configurable: true
  15179. });
  15180. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15181. get: function () {
  15182. return this._rigPostProcess;
  15183. },
  15184. enumerable: true,
  15185. configurable: true
  15186. });
  15187. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15188. // invalidate framebuffer
  15189. if (this._postProcesses.length > 0) {
  15190. this._postProcesses[0].markTextureDirty();
  15191. }
  15192. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15193. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15194. var cam = this._rigCameras[i];
  15195. var rigPostProcess = cam._rigPostProcess;
  15196. // for VR rig, there does not have to be a post process
  15197. if (rigPostProcess) {
  15198. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15199. if (isPass) {
  15200. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15201. cam.isIntermediate = this._postProcesses.length === 0;
  15202. }
  15203. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15204. rigPostProcess.markTextureDirty();
  15205. }
  15206. else {
  15207. cam._postProcesses = this._postProcesses.slice(0);
  15208. }
  15209. }
  15210. };
  15211. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15212. if (insertAt === void 0) { insertAt = null; }
  15213. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15214. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15215. return 0;
  15216. }
  15217. if (insertAt == null || insertAt < 0) {
  15218. this._postProcesses.push(postProcess);
  15219. }
  15220. else {
  15221. this._postProcesses.splice(insertAt, 0, postProcess);
  15222. }
  15223. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15224. return this._postProcesses.indexOf(postProcess);
  15225. };
  15226. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15227. if (atIndices === void 0) { atIndices = null; }
  15228. var result = [];
  15229. var i;
  15230. var index;
  15231. if (!atIndices) {
  15232. var idx = this._postProcesses.indexOf(postProcess);
  15233. if (idx !== -1) {
  15234. this._postProcesses.splice(idx, 1);
  15235. }
  15236. }
  15237. else {
  15238. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15239. // iterate descending, so can just splice as we go
  15240. for (i = atIndices.length - 1; i >= 0; i--) {
  15241. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15242. result.push(i);
  15243. continue;
  15244. }
  15245. index = atIndices[i];
  15246. this._postProcesses.splice(index, 1);
  15247. }
  15248. }
  15249. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15250. return result;
  15251. };
  15252. Camera.prototype.getWorldMatrix = function () {
  15253. if (!this._worldMatrix) {
  15254. this._worldMatrix = BABYLON.Matrix.Identity();
  15255. }
  15256. var viewMatrix = this.getViewMatrix();
  15257. viewMatrix.invertToRef(this._worldMatrix);
  15258. return this._worldMatrix;
  15259. };
  15260. Camera.prototype._getViewMatrix = function () {
  15261. return BABYLON.Matrix.Identity();
  15262. };
  15263. Camera.prototype.getViewMatrix = function (force) {
  15264. if (!force && this._isSynchronizedViewMatrix()) {
  15265. return this._computedViewMatrix;
  15266. }
  15267. this._computedViewMatrix = this._getViewMatrix();
  15268. this._currentRenderId = this.getScene().getRenderId();
  15269. this._refreshFrustumPlanes = true;
  15270. if (!this.parent || !this.parent.getWorldMatrix) {
  15271. this._globalPosition.copyFrom(this.position);
  15272. }
  15273. else {
  15274. if (!this._worldMatrix) {
  15275. this._worldMatrix = BABYLON.Matrix.Identity();
  15276. }
  15277. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15278. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15279. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15280. this._computedViewMatrix.invert();
  15281. this._markSyncedWithParent();
  15282. }
  15283. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15284. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15285. }
  15286. this.onViewMatrixChangedObservable.notifyObservers(this);
  15287. return this._computedViewMatrix;
  15288. };
  15289. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15290. this._doNotComputeProjectionMatrix = true;
  15291. if (projection !== undefined) {
  15292. this._projectionMatrix = projection;
  15293. }
  15294. };
  15295. ;
  15296. Camera.prototype.unfreezeProjectionMatrix = function () {
  15297. this._doNotComputeProjectionMatrix = false;
  15298. };
  15299. ;
  15300. Camera.prototype.getProjectionMatrix = function (force) {
  15301. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15302. return this._projectionMatrix;
  15303. }
  15304. this._refreshFrustumPlanes = true;
  15305. var engine = this.getEngine();
  15306. var scene = this.getScene();
  15307. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15308. if (this.minZ <= 0) {
  15309. this.minZ = 0.1;
  15310. }
  15311. if (scene.useRightHandedSystem) {
  15312. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15313. }
  15314. else {
  15315. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15316. }
  15317. }
  15318. else {
  15319. var halfWidth = engine.getRenderWidth() / 2.0;
  15320. var halfHeight = engine.getRenderHeight() / 2.0;
  15321. if (scene.useRightHandedSystem) {
  15322. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15323. }
  15324. else {
  15325. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15326. }
  15327. }
  15328. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15329. return this._projectionMatrix;
  15330. };
  15331. Camera.prototype.getTranformationMatrix = function () {
  15332. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15333. return this._transformMatrix;
  15334. };
  15335. Camera.prototype.updateFrustumPlanes = function () {
  15336. if (!this._refreshFrustumPlanes) {
  15337. return;
  15338. }
  15339. this.getTranformationMatrix();
  15340. if (!this._frustumPlanes) {
  15341. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15342. }
  15343. else {
  15344. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15345. }
  15346. this._refreshFrustumPlanes = false;
  15347. };
  15348. Camera.prototype.isInFrustum = function (target) {
  15349. this.updateFrustumPlanes();
  15350. return target.isInFrustum(this._frustumPlanes);
  15351. };
  15352. Camera.prototype.isCompletelyInFrustum = function (target) {
  15353. this.updateFrustumPlanes();
  15354. return target.isCompletelyInFrustum(this._frustumPlanes);
  15355. };
  15356. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15357. if (length === void 0) { length = 100; }
  15358. if (!transform) {
  15359. transform = this.getWorldMatrix();
  15360. }
  15361. if (!origin) {
  15362. origin = this.position;
  15363. }
  15364. var forward = new BABYLON.Vector3(0, 0, 1);
  15365. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15366. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15367. return new BABYLON.Ray(origin, direction, length);
  15368. };
  15369. Camera.prototype.dispose = function () {
  15370. // Observables
  15371. this.onViewMatrixChangedObservable.clear();
  15372. this.onProjectionMatrixChangedObservable.clear();
  15373. this.onAfterCheckInputsObservable.clear();
  15374. // Inputs
  15375. if (this.inputs) {
  15376. this.inputs.clear();
  15377. }
  15378. // Animations
  15379. this.getScene().stopAnimation(this);
  15380. // Remove from scene
  15381. this.getScene().removeCamera(this);
  15382. while (this._rigCameras.length > 0) {
  15383. this._rigCameras.pop().dispose();
  15384. }
  15385. // Postprocesses
  15386. var i = this._postProcesses.length;
  15387. while (--i >= 0) {
  15388. this._postProcesses[i].dispose(this);
  15389. }
  15390. // Render targets
  15391. var i = this.customRenderTargets.length;
  15392. while (--i >= 0) {
  15393. this.customRenderTargets[i].dispose();
  15394. }
  15395. this.customRenderTargets = [];
  15396. // Active Meshes
  15397. this._activeMeshes.dispose();
  15398. _super.prototype.dispose.call(this);
  15399. };
  15400. Object.defineProperty(Camera.prototype, "leftCamera", {
  15401. // ---- Camera rigs section ----
  15402. get: function () {
  15403. if (this._rigCameras.length < 1) {
  15404. return undefined;
  15405. }
  15406. return this._rigCameras[0];
  15407. },
  15408. enumerable: true,
  15409. configurable: true
  15410. });
  15411. Object.defineProperty(Camera.prototype, "rightCamera", {
  15412. get: function () {
  15413. if (this._rigCameras.length < 2) {
  15414. return undefined;
  15415. }
  15416. return this._rigCameras[1];
  15417. },
  15418. enumerable: true,
  15419. configurable: true
  15420. });
  15421. Camera.prototype.getLeftTarget = function () {
  15422. if (this._rigCameras.length < 1) {
  15423. return undefined;
  15424. }
  15425. return this._rigCameras[0].getTarget();
  15426. };
  15427. Camera.prototype.getRightTarget = function () {
  15428. if (this._rigCameras.length < 2) {
  15429. return undefined;
  15430. }
  15431. return this._rigCameras[1].getTarget();
  15432. };
  15433. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15434. while (this._rigCameras.length > 0) {
  15435. this._rigCameras.pop().dispose();
  15436. }
  15437. this.cameraRigMode = mode;
  15438. this._cameraRigParams = {};
  15439. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15440. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15441. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15442. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15443. // create the rig cameras, unless none
  15444. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15445. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15446. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15447. }
  15448. switch (this.cameraRigMode) {
  15449. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15450. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15451. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15452. break;
  15453. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15454. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15455. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15456. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15457. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15458. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15459. break;
  15460. case Camera.RIG_MODE_VR:
  15461. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15462. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15463. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15464. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15465. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15466. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15467. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15468. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15469. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15470. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15471. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15472. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15473. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15474. if (metrics.compensateDistortion) {
  15475. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15476. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15477. }
  15478. break;
  15479. case Camera.RIG_MODE_WEBVR:
  15480. if (rigParams.vrDisplay) {
  15481. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15482. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15483. //Left eye
  15484. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15485. this._rigCameras[0].setCameraRigParameter("left", true);
  15486. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15487. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15488. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15489. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15490. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15491. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15492. this._rigCameras[0].parent = this;
  15493. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15494. //Right eye
  15495. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15496. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15497. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15498. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15499. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15500. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15501. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15502. this._rigCameras[1].parent = this;
  15503. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15504. }
  15505. break;
  15506. }
  15507. this._cascadePostProcessesToRigCams();
  15508. this.
  15509. update();
  15510. };
  15511. Camera.prototype._getVRProjectionMatrix = function () {
  15512. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15513. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15514. return this._projectionMatrix;
  15515. };
  15516. Camera.prototype._updateCameraRotationMatrix = function () {
  15517. //Here for WebVR
  15518. };
  15519. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15520. //Here for WebVR
  15521. };
  15522. /**
  15523. * This function MUST be overwritten by the different WebVR cameras available.
  15524. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15525. */
  15526. Camera.prototype._getWebVRProjectionMatrix = function () {
  15527. return BABYLON.Matrix.Identity();
  15528. };
  15529. /**
  15530. * This function MUST be overwritten by the different WebVR cameras available.
  15531. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15532. */
  15533. Camera.prototype._getWebVRViewMatrix = function () {
  15534. return BABYLON.Matrix.Identity();
  15535. };
  15536. Camera.prototype.setCameraRigParameter = function (name, value) {
  15537. if (!this._cameraRigParams) {
  15538. this._cameraRigParams = {};
  15539. }
  15540. this._cameraRigParams[name] = value;
  15541. //provisionnally:
  15542. if (name === "interaxialDistance") {
  15543. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15544. }
  15545. };
  15546. /**
  15547. * needs to be overridden by children so sub has required properties to be copied
  15548. */
  15549. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15550. return null;
  15551. };
  15552. /**
  15553. * May need to be overridden by children
  15554. */
  15555. Camera.prototype._updateRigCameras = function () {
  15556. for (var i = 0; i < this._rigCameras.length; i++) {
  15557. this._rigCameras[i].minZ = this.minZ;
  15558. this._rigCameras[i].maxZ = this.maxZ;
  15559. this._rigCameras[i].fov = this.fov;
  15560. }
  15561. // only update viewport when ANAGLYPH
  15562. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15563. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15564. }
  15565. };
  15566. Camera.prototype._setupInputs = function () {
  15567. };
  15568. Camera.prototype.serialize = function () {
  15569. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15570. // Type
  15571. serializationObject.type = this.getClassName();
  15572. // Parent
  15573. if (this.parent) {
  15574. serializationObject.parentId = this.parent.id;
  15575. }
  15576. if (this.inputs) {
  15577. this.inputs.serialize(serializationObject);
  15578. }
  15579. // Animations
  15580. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15581. serializationObject.ranges = this.serializeAnimationRanges();
  15582. return serializationObject;
  15583. };
  15584. Camera.prototype.clone = function (name) {
  15585. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15586. };
  15587. Camera.prototype.getDirection = function (localAxis) {
  15588. var result = BABYLON.Vector3.Zero();
  15589. this.getDirectionToRef(localAxis, result);
  15590. return result;
  15591. };
  15592. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15593. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15594. };
  15595. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15596. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15597. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15598. switch (type) {
  15599. case "ArcRotateCamera":
  15600. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15601. case "DeviceOrientationCamera":
  15602. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15603. case "FollowCamera":
  15604. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15605. case "ArcFollowCamera":
  15606. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15607. case "GamepadCamera":
  15608. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15609. case "TouchCamera":
  15610. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15611. case "VirtualJoysticksCamera":
  15612. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15613. case "WebVRFreeCamera":
  15614. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15615. case "WebVRGamepadCamera":
  15616. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15617. case "VRDeviceOrientationFreeCamera":
  15618. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15619. case "VRDeviceOrientationGamepadCamera":
  15620. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15621. case "AnaglyphArcRotateCamera":
  15622. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15623. case "AnaglyphFreeCamera":
  15624. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15625. case "AnaglyphGamepadCamera":
  15626. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15627. case "AnaglyphUniversalCamera":
  15628. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15629. case "StereoscopicArcRotateCamera":
  15630. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15631. case "StereoscopicFreeCamera":
  15632. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15633. case "StereoscopicGamepadCamera":
  15634. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15635. case "StereoscopicUniversalCamera":
  15636. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15637. case "FreeCamera":// Forcing Universal here
  15638. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15639. default:// Universal Camera is the default value
  15640. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15641. }
  15642. };
  15643. Camera.Parse = function (parsedCamera, scene) {
  15644. var type = parsedCamera.type;
  15645. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15646. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15647. // Parent
  15648. if (parsedCamera.parentId) {
  15649. camera._waitingParentId = parsedCamera.parentId;
  15650. }
  15651. //If camera has an input manager, let it parse inputs settings
  15652. if (camera.inputs) {
  15653. camera.inputs.parse(parsedCamera);
  15654. camera._setupInputs();
  15655. }
  15656. if (camera.setPosition) {
  15657. camera.position.copyFromFloats(0, 0, 0);
  15658. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15659. }
  15660. // Target
  15661. if (parsedCamera.target) {
  15662. if (camera.setTarget) {
  15663. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15664. }
  15665. }
  15666. // Apply 3d rig, when found
  15667. if (parsedCamera.cameraRigMode) {
  15668. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15669. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15670. }
  15671. // Animations
  15672. if (parsedCamera.animations) {
  15673. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15674. var parsedAnimation = parsedCamera.animations[animationIndex];
  15675. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15676. }
  15677. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15678. }
  15679. if (parsedCamera.autoAnimate) {
  15680. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15681. }
  15682. return camera;
  15683. };
  15684. // Statics
  15685. Camera._PERSPECTIVE_CAMERA = 0;
  15686. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15687. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15688. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15689. Camera._RIG_MODE_NONE = 0;
  15690. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15691. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15692. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15693. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15694. Camera._RIG_MODE_VR = 20;
  15695. Camera._RIG_MODE_WEBVR = 21;
  15696. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15697. __decorate([
  15698. BABYLON.serializeAsVector3()
  15699. ], Camera.prototype, "position", void 0);
  15700. __decorate([
  15701. BABYLON.serializeAsVector3()
  15702. ], Camera.prototype, "upVector", void 0);
  15703. __decorate([
  15704. BABYLON.serialize()
  15705. ], Camera.prototype, "orthoLeft", void 0);
  15706. __decorate([
  15707. BABYLON.serialize()
  15708. ], Camera.prototype, "orthoRight", void 0);
  15709. __decorate([
  15710. BABYLON.serialize()
  15711. ], Camera.prototype, "orthoBottom", void 0);
  15712. __decorate([
  15713. BABYLON.serialize()
  15714. ], Camera.prototype, "orthoTop", void 0);
  15715. __decorate([
  15716. BABYLON.serialize()
  15717. ], Camera.prototype, "fov", void 0);
  15718. __decorate([
  15719. BABYLON.serialize()
  15720. ], Camera.prototype, "minZ", void 0);
  15721. __decorate([
  15722. BABYLON.serialize()
  15723. ], Camera.prototype, "maxZ", void 0);
  15724. __decorate([
  15725. BABYLON.serialize()
  15726. ], Camera.prototype, "inertia", void 0);
  15727. __decorate([
  15728. BABYLON.serialize()
  15729. ], Camera.prototype, "mode", void 0);
  15730. __decorate([
  15731. BABYLON.serialize()
  15732. ], Camera.prototype, "layerMask", void 0);
  15733. __decorate([
  15734. BABYLON.serialize()
  15735. ], Camera.prototype, "fovMode", void 0);
  15736. __decorate([
  15737. BABYLON.serialize()
  15738. ], Camera.prototype, "cameraRigMode", void 0);
  15739. __decorate([
  15740. BABYLON.serialize()
  15741. ], Camera.prototype, "interaxialDistance", void 0);
  15742. __decorate([
  15743. BABYLON.serialize()
  15744. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15745. return Camera;
  15746. }(BABYLON.Node));
  15747. BABYLON.Camera = Camera;
  15748. })(BABYLON || (BABYLON = {}));
  15749. //# sourceMappingURL=babylon.camera.js.map
  15750. var BABYLON;
  15751. (function (BABYLON) {
  15752. var RenderingManager = (function () {
  15753. function RenderingManager(scene) {
  15754. this._renderingGroups = new Array();
  15755. this._autoClearDepthStencil = {};
  15756. this._customOpaqueSortCompareFn = {};
  15757. this._customAlphaTestSortCompareFn = {};
  15758. this._customTransparentSortCompareFn = {};
  15759. this._renderinGroupInfo = null;
  15760. this._scene = scene;
  15761. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15762. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15763. }
  15764. }
  15765. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15766. if (depth === void 0) { depth = true; }
  15767. if (stencil === void 0) { stencil = true; }
  15768. if (this._depthStencilBufferAlreadyCleaned) {
  15769. return;
  15770. }
  15771. this._scene.getEngine().clear(null, false, depth, stencil);
  15772. this._depthStencilBufferAlreadyCleaned = true;
  15773. };
  15774. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15775. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15776. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15777. var info = null;
  15778. if (observable) {
  15779. if (!this._renderinGroupInfo) {
  15780. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15781. }
  15782. info = this._renderinGroupInfo;
  15783. info.scene = this._scene;
  15784. info.camera = this._scene.activeCamera;
  15785. }
  15786. // Dispatch sprites
  15787. if (renderSprites) {
  15788. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15789. var manager = this._scene.spriteManagers[index];
  15790. this.dispatchSprites(manager);
  15791. }
  15792. }
  15793. // Render
  15794. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15795. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15796. var renderingGroup = this._renderingGroups[index];
  15797. if (!renderingGroup && !observable)
  15798. continue;
  15799. this._currentIndex = index;
  15800. var renderingGroupMask = 0;
  15801. // Fire PRECLEAR stage
  15802. if (observable) {
  15803. renderingGroupMask = Math.pow(2, index);
  15804. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15805. info.renderingGroupId = index;
  15806. observable.notifyObservers(info, renderingGroupMask);
  15807. }
  15808. // Clear depth/stencil if needed
  15809. if (RenderingManager.AUTOCLEAR) {
  15810. var autoClear = this._autoClearDepthStencil[index];
  15811. if (autoClear && autoClear.autoClear) {
  15812. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15813. }
  15814. }
  15815. if (observable) {
  15816. // Fire PREOPAQUE stage
  15817. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15818. observable.notifyObservers(info, renderingGroupMask);
  15819. // Fire PRETRANSPARENT stage
  15820. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15821. observable.notifyObservers(info, renderingGroupMask);
  15822. }
  15823. if (renderingGroup)
  15824. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15825. // Fire POSTTRANSPARENT stage
  15826. if (observable) {
  15827. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15828. observable.notifyObservers(info, renderingGroupMask);
  15829. }
  15830. }
  15831. };
  15832. RenderingManager.prototype.reset = function () {
  15833. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15834. var renderingGroup = this._renderingGroups[index];
  15835. if (renderingGroup) {
  15836. renderingGroup.prepare();
  15837. }
  15838. }
  15839. };
  15840. RenderingManager.prototype.dispose = function () {
  15841. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15842. var renderingGroup = this._renderingGroups[index];
  15843. if (renderingGroup) {
  15844. renderingGroup.dispose();
  15845. }
  15846. }
  15847. this._renderingGroups.length = 0;
  15848. };
  15849. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15850. if (!this._renderingGroups[renderingGroupId]) {
  15851. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15852. }
  15853. };
  15854. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15855. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15856. this._prepareRenderingGroup(renderingGroupId);
  15857. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15858. };
  15859. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15860. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15861. this._prepareRenderingGroup(renderingGroupId);
  15862. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15863. };
  15864. RenderingManager.prototype.dispatch = function (subMesh) {
  15865. var mesh = subMesh.getMesh();
  15866. var renderingGroupId = mesh.renderingGroupId || 0;
  15867. this._prepareRenderingGroup(renderingGroupId);
  15868. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15869. };
  15870. /**
  15871. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15872. * This allowed control for front to back rendering or reversly depending of the special needs.
  15873. *
  15874. * @param renderingGroupId The rendering group id corresponding to its index
  15875. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15876. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15877. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15878. */
  15879. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15880. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15881. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15882. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15883. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15884. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15885. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15886. if (this._renderingGroups[renderingGroupId]) {
  15887. var group = this._renderingGroups[renderingGroupId];
  15888. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15889. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15890. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15891. }
  15892. };
  15893. /**
  15894. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15895. *
  15896. * @param renderingGroupId The rendering group id corresponding to its index
  15897. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15898. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15899. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15900. */
  15901. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15902. if (depth === void 0) { depth = true; }
  15903. if (stencil === void 0) { stencil = true; }
  15904. this._autoClearDepthStencil[renderingGroupId] = {
  15905. autoClear: autoClearDepthStencil,
  15906. depth: depth,
  15907. stencil: stencil
  15908. };
  15909. };
  15910. /**
  15911. * The max id used for rendering groups (not included)
  15912. */
  15913. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15914. /**
  15915. * The min id used for rendering groups (included)
  15916. */
  15917. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15918. /**
  15919. * Used to globally prevent autoclearing scenes.
  15920. */
  15921. RenderingManager.AUTOCLEAR = true;
  15922. return RenderingManager;
  15923. }());
  15924. BABYLON.RenderingManager = RenderingManager;
  15925. })(BABYLON || (BABYLON = {}));
  15926. //# sourceMappingURL=babylon.renderingManager.js.map
  15927. var BABYLON;
  15928. (function (BABYLON) {
  15929. var RenderingGroup = (function () {
  15930. /**
  15931. * Creates a new rendering group.
  15932. * @param index The rendering group index
  15933. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15934. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15935. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15936. */
  15937. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15938. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15939. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15940. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15941. this.index = index;
  15942. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15943. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15944. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15945. this._particleSystems = new BABYLON.SmartArray(256);
  15946. this._spriteManagers = new BABYLON.SmartArray(256);
  15947. this._edgesRenderers = new BABYLON.SmartArray(16);
  15948. this._scene = scene;
  15949. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15950. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15951. this.transparentSortCompareFn = transparentSortCompareFn;
  15952. }
  15953. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15954. /**
  15955. * Set the opaque sort comparison function.
  15956. * If null the sub meshes will be render in the order they were created
  15957. */
  15958. set: function (value) {
  15959. this._opaqueSortCompareFn = value;
  15960. if (value) {
  15961. this._renderOpaque = this.renderOpaqueSorted;
  15962. }
  15963. else {
  15964. this._renderOpaque = RenderingGroup.renderUnsorted;
  15965. }
  15966. },
  15967. enumerable: true,
  15968. configurable: true
  15969. });
  15970. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15971. /**
  15972. * Set the alpha test sort comparison function.
  15973. * If null the sub meshes will be render in the order they were created
  15974. */
  15975. set: function (value) {
  15976. this._alphaTestSortCompareFn = value;
  15977. if (value) {
  15978. this._renderAlphaTest = this.renderAlphaTestSorted;
  15979. }
  15980. else {
  15981. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15982. }
  15983. },
  15984. enumerable: true,
  15985. configurable: true
  15986. });
  15987. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15988. /**
  15989. * Set the transparent sort comparison function.
  15990. * If null the sub meshes will be render in the order they were created
  15991. */
  15992. set: function (value) {
  15993. if (value) {
  15994. this._transparentSortCompareFn = value;
  15995. }
  15996. else {
  15997. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15998. }
  15999. this._renderTransparent = this.renderTransparentSorted;
  16000. },
  16001. enumerable: true,
  16002. configurable: true
  16003. });
  16004. /**
  16005. * Render all the sub meshes contained in the group.
  16006. * @param customRenderFunction Used to override the default render behaviour of the group.
  16007. * @returns true if rendered some submeshes.
  16008. */
  16009. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16010. if (customRenderFunction) {
  16011. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  16012. return;
  16013. }
  16014. var engine = this._scene.getEngine();
  16015. // Opaque
  16016. if (this._opaqueSubMeshes.length !== 0) {
  16017. this._renderOpaque(this._opaqueSubMeshes);
  16018. }
  16019. // Alpha test
  16020. if (this._alphaTestSubMeshes.length !== 0) {
  16021. engine.setAlphaTesting(true);
  16022. this._renderAlphaTest(this._alphaTestSubMeshes);
  16023. engine.setAlphaTesting(false);
  16024. }
  16025. var stencilState = engine.getStencilBuffer();
  16026. engine.setStencilBuffer(false);
  16027. // Sprites
  16028. if (renderSprites) {
  16029. this._renderSprites();
  16030. }
  16031. // Particles
  16032. if (renderParticles) {
  16033. this._renderParticles(activeMeshes);
  16034. }
  16035. if (this.onBeforeTransparentRendering) {
  16036. this.onBeforeTransparentRendering();
  16037. }
  16038. // Transparent
  16039. if (this._transparentSubMeshes.length !== 0) {
  16040. this._renderTransparent(this._transparentSubMeshes);
  16041. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16042. }
  16043. // Set back stencil to false in case it changes before the edge renderer.
  16044. engine.setStencilBuffer(false);
  16045. // Edges
  16046. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16047. this._edgesRenderers.data[edgesRendererIndex].render();
  16048. }
  16049. // Restore Stencil state.
  16050. engine.setStencilBuffer(stencilState);
  16051. };
  16052. /**
  16053. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16054. * @param subMeshes The submeshes to render
  16055. */
  16056. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16057. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16058. };
  16059. /**
  16060. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16061. * @param subMeshes The submeshes to render
  16062. */
  16063. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16064. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16065. };
  16066. /**
  16067. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16068. * @param subMeshes The submeshes to render
  16069. */
  16070. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16071. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16072. };
  16073. /**
  16074. * Renders the submeshes in a specified order.
  16075. * @param subMeshes The submeshes to sort before render
  16076. * @param sortCompareFn The comparison function use to sort
  16077. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16078. * @param transparent Specifies to activate blending if true
  16079. */
  16080. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16081. var subIndex = 0;
  16082. var subMesh;
  16083. for (; subIndex < subMeshes.length; subIndex++) {
  16084. subMesh = subMeshes.data[subIndex];
  16085. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16086. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16087. }
  16088. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16089. sortedArray.sort(sortCompareFn);
  16090. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16091. subMesh = sortedArray[subIndex];
  16092. subMesh.render(transparent);
  16093. }
  16094. };
  16095. /**
  16096. * Renders the submeshes in the order they were dispatched (no sort applied).
  16097. * @param subMeshes The submeshes to render
  16098. */
  16099. RenderingGroup.renderUnsorted = function (subMeshes) {
  16100. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16101. var submesh = subMeshes.data[subIndex];
  16102. submesh.render(false);
  16103. }
  16104. };
  16105. /**
  16106. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16107. * are rendered back to front if in the same alpha index.
  16108. *
  16109. * @param a The first submesh
  16110. * @param b The second submesh
  16111. * @returns The result of the comparison
  16112. */
  16113. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16114. // Alpha index first
  16115. if (a._alphaIndex > b._alphaIndex) {
  16116. return 1;
  16117. }
  16118. if (a._alphaIndex < b._alphaIndex) {
  16119. return -1;
  16120. }
  16121. // Then distance to camera
  16122. return RenderingGroup.backToFrontSortCompare(a, b);
  16123. };
  16124. /**
  16125. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16126. * are rendered back to front.
  16127. *
  16128. * @param a The first submesh
  16129. * @param b The second submesh
  16130. * @returns The result of the comparison
  16131. */
  16132. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16133. // Then distance to camera
  16134. if (a._distanceToCamera < b._distanceToCamera) {
  16135. return 1;
  16136. }
  16137. if (a._distanceToCamera > b._distanceToCamera) {
  16138. return -1;
  16139. }
  16140. return 0;
  16141. };
  16142. /**
  16143. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16144. * are rendered front to back (prevent overdraw).
  16145. *
  16146. * @param a The first submesh
  16147. * @param b The second submesh
  16148. * @returns The result of the comparison
  16149. */
  16150. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16151. // Then distance to camera
  16152. if (a._distanceToCamera < b._distanceToCamera) {
  16153. return -1;
  16154. }
  16155. if (a._distanceToCamera > b._distanceToCamera) {
  16156. return 1;
  16157. }
  16158. return 0;
  16159. };
  16160. /**
  16161. * Resets the different lists of submeshes to prepare a new frame.
  16162. */
  16163. RenderingGroup.prototype.prepare = function () {
  16164. this._opaqueSubMeshes.reset();
  16165. this._transparentSubMeshes.reset();
  16166. this._alphaTestSubMeshes.reset();
  16167. this._particleSystems.reset();
  16168. this._spriteManagers.reset();
  16169. this._edgesRenderers.reset();
  16170. };
  16171. RenderingGroup.prototype.dispose = function () {
  16172. this._opaqueSubMeshes.dispose();
  16173. this._transparentSubMeshes.dispose();
  16174. this._alphaTestSubMeshes.dispose();
  16175. this._particleSystems.dispose();
  16176. this._spriteManagers.dispose();
  16177. this._edgesRenderers.dispose();
  16178. };
  16179. /**
  16180. * Inserts the submesh in its correct queue depending on its material.
  16181. * @param subMesh The submesh to dispatch
  16182. */
  16183. RenderingGroup.prototype.dispatch = function (subMesh) {
  16184. var material = subMesh.getMaterial();
  16185. var mesh = subMesh.getMesh();
  16186. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16187. this._transparentSubMeshes.push(subMesh);
  16188. }
  16189. else if (material.needAlphaTesting()) {
  16190. this._alphaTestSubMeshes.push(subMesh);
  16191. }
  16192. else {
  16193. this._opaqueSubMeshes.push(subMesh); // Opaque
  16194. }
  16195. if (mesh._edgesRenderer) {
  16196. this._edgesRenderers.push(mesh._edgesRenderer);
  16197. }
  16198. };
  16199. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16200. this._spriteManagers.push(spriteManager);
  16201. };
  16202. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16203. this._particleSystems.push(particleSystem);
  16204. };
  16205. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16206. if (this._particleSystems.length === 0) {
  16207. return;
  16208. }
  16209. // Particles
  16210. var activeCamera = this._scene.activeCamera;
  16211. this._scene._particlesDuration.beginMonitoring();
  16212. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16213. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16214. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16215. continue;
  16216. }
  16217. var emitter = particleSystem.emitter;
  16218. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16219. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16220. }
  16221. }
  16222. this._scene._particlesDuration.endMonitoring(false);
  16223. };
  16224. RenderingGroup.prototype._renderSprites = function () {
  16225. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16226. return;
  16227. }
  16228. // Sprites
  16229. var activeCamera = this._scene.activeCamera;
  16230. this._scene._spritesDuration.beginMonitoring();
  16231. for (var id = 0; id < this._spriteManagers.length; id++) {
  16232. var spriteManager = this._spriteManagers.data[id];
  16233. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16234. spriteManager.render();
  16235. }
  16236. }
  16237. this._scene._spritesDuration.endMonitoring(false);
  16238. };
  16239. return RenderingGroup;
  16240. }());
  16241. BABYLON.RenderingGroup = RenderingGroup;
  16242. })(BABYLON || (BABYLON = {}));
  16243. //# sourceMappingURL=babylon.renderingGroup.js.map
  16244. var BABYLON;
  16245. (function (BABYLON) {
  16246. var ClickInfo = (function () {
  16247. function ClickInfo() {
  16248. this._singleClick = false;
  16249. this._doubleClick = false;
  16250. this._hasSwiped = false;
  16251. this._ignore = false;
  16252. }
  16253. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16254. get: function () {
  16255. return this._singleClick;
  16256. },
  16257. set: function (b) {
  16258. this._singleClick = b;
  16259. },
  16260. enumerable: true,
  16261. configurable: true
  16262. });
  16263. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16264. get: function () {
  16265. return this._doubleClick;
  16266. },
  16267. set: function (b) {
  16268. this._doubleClick = b;
  16269. },
  16270. enumerable: true,
  16271. configurable: true
  16272. });
  16273. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16274. get: function () {
  16275. return this._hasSwiped;
  16276. },
  16277. set: function (b) {
  16278. this._hasSwiped = b;
  16279. },
  16280. enumerable: true,
  16281. configurable: true
  16282. });
  16283. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16284. get: function () {
  16285. return this._ignore;
  16286. },
  16287. set: function (b) {
  16288. this._ignore = b;
  16289. },
  16290. enumerable: true,
  16291. configurable: true
  16292. });
  16293. return ClickInfo;
  16294. }());
  16295. /**
  16296. * This class is used by the onRenderingGroupObservable
  16297. */
  16298. var RenderingGroupInfo = (function () {
  16299. function RenderingGroupInfo() {
  16300. }
  16301. /**
  16302. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16303. * This stage will be fired no matter what
  16304. */
  16305. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16306. /**
  16307. * Called before opaque object are rendered.
  16308. * This stage will be fired only if there's 3D Opaque content to render
  16309. */
  16310. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16311. /**
  16312. * Called after the opaque objects are rendered and before the transparent ones
  16313. * This stage will be fired only if there's 3D transparent content to render
  16314. */
  16315. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16316. /**
  16317. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16318. * This stage will be fired no matter what
  16319. */
  16320. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16321. return RenderingGroupInfo;
  16322. }());
  16323. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16324. /**
  16325. * Represents a scene to be rendered by the engine.
  16326. * @see http://doc.babylonjs.com/page.php?p=21911
  16327. */
  16328. var Scene = (function () {
  16329. /**
  16330. * @constructor
  16331. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16332. */
  16333. function Scene(engine) {
  16334. // Members
  16335. this.autoClear = true;
  16336. this.autoClearDepthAndStencil = true;
  16337. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16338. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16339. this.forceWireframe = false;
  16340. this._forcePointsCloud = false;
  16341. this.forceShowBoundingBoxes = false;
  16342. this.animationsEnabled = true;
  16343. this.constantlyUpdateMeshUnderPointer = false;
  16344. this.hoverCursor = "pointer";
  16345. this.defaultCursor = "";
  16346. // Metadata
  16347. this.metadata = null;
  16348. // Events
  16349. /**
  16350. * An event triggered when the scene is disposed.
  16351. * @type {BABYLON.Observable}
  16352. */
  16353. this.onDisposeObservable = new BABYLON.Observable();
  16354. /**
  16355. * An event triggered before rendering the scene
  16356. * @type {BABYLON.Observable}
  16357. */
  16358. this.onBeforeRenderObservable = new BABYLON.Observable();
  16359. /**
  16360. * An event triggered after rendering the scene
  16361. * @type {BABYLON.Observable}
  16362. */
  16363. this.onAfterRenderObservable = new BABYLON.Observable();
  16364. /**
  16365. * An event triggered when the scene is ready
  16366. * @type {BABYLON.Observable}
  16367. */
  16368. this.onReadyObservable = new BABYLON.Observable();
  16369. /**
  16370. * An event triggered before rendering a camera
  16371. * @type {BABYLON.Observable}
  16372. */
  16373. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16374. /**
  16375. * An event triggered after rendering a camera
  16376. * @type {BABYLON.Observable}
  16377. */
  16378. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16379. /**
  16380. * An event triggered when a camera is created
  16381. * @type {BABYLON.Observable}
  16382. */
  16383. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16384. /**
  16385. * An event triggered when a camera is removed
  16386. * @type {BABYLON.Observable}
  16387. */
  16388. this.onCameraRemovedObservable = new BABYLON.Observable();
  16389. /**
  16390. * An event triggered when a light is created
  16391. * @type {BABYLON.Observable}
  16392. */
  16393. this.onNewLightAddedObservable = new BABYLON.Observable();
  16394. /**
  16395. * An event triggered when a light is removed
  16396. * @type {BABYLON.Observable}
  16397. */
  16398. this.onLightRemovedObservable = new BABYLON.Observable();
  16399. /**
  16400. * An event triggered when a geometry is created
  16401. * @type {BABYLON.Observable}
  16402. */
  16403. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16404. /**
  16405. * An event triggered when a geometry is removed
  16406. * @type {BABYLON.Observable}
  16407. */
  16408. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16409. /**
  16410. * An event triggered when a mesh is created
  16411. * @type {BABYLON.Observable}
  16412. */
  16413. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16414. /**
  16415. * An event triggered when a mesh is removed
  16416. * @type {BABYLON.Observable}
  16417. */
  16418. this.onMeshRemovedObservable = new BABYLON.Observable();
  16419. /**
  16420. * An event triggered before calculating deterministic simulation step
  16421. * @type {BABYLON.Observable}
  16422. */
  16423. this.onBeforeStepObservable = new BABYLON.Observable();
  16424. /**
  16425. * An event triggered after calculating deterministic simulation step
  16426. * @type {BABYLON.Observable}
  16427. */
  16428. this.onAfterStepObservable = new BABYLON.Observable();
  16429. /**
  16430. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16431. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16432. * 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)
  16433. */
  16434. this.onRenderingGroupObservable = new BABYLON.Observable();
  16435. // Animations
  16436. this.animations = [];
  16437. /**
  16438. * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
  16439. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  16440. */
  16441. this.onPrePointerObservable = new BABYLON.Observable();
  16442. /**
  16443. * Observable event triggered each time an input event is received from the rendering canvas
  16444. */
  16445. this.onPointerObservable = new BABYLON.Observable();
  16446. this._meshPickProceed = false;
  16447. this._previousHasSwiped = false;
  16448. this._currentPickResult = null;
  16449. this._previousPickResult = null;
  16450. this._isButtonPressed = false;
  16451. this._doubleClickOccured = false;
  16452. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16453. this.cameraToUseForPointers = null;
  16454. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16455. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16456. this._startingPointerTime = 0;
  16457. this._previousStartingPointerTime = 0;
  16458. // Deterministic lockstep
  16459. this._timeAccumulator = 0;
  16460. this._currentStepId = 0;
  16461. this._currentInternalStep = 0;
  16462. // Keyboard
  16463. /**
  16464. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  16465. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  16466. */
  16467. this.onPreKeyboardObservable = new BABYLON.Observable();
  16468. /**
  16469. * Observable event triggered each time an keyboard event is received from the hosting window
  16470. */
  16471. this.onKeyboardObservable = new BABYLON.Observable();
  16472. // Coordinate system
  16473. /**
  16474. * use right-handed coordinate system on this scene.
  16475. * @type {boolean}
  16476. */
  16477. this._useRightHandedSystem = false;
  16478. // Fog
  16479. this._fogEnabled = true;
  16480. this._fogMode = Scene.FOGMODE_NONE;
  16481. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16482. this.fogDensity = 0.1;
  16483. this.fogStart = 0;
  16484. this.fogEnd = 1000.0;
  16485. // Lights
  16486. /**
  16487. * is shadow enabled on this scene.
  16488. * @type {boolean}
  16489. */
  16490. this._shadowsEnabled = true;
  16491. /**
  16492. * is light enabled on this scene.
  16493. * @type {boolean}
  16494. */
  16495. this._lightsEnabled = true;
  16496. /**
  16497. * All of the lights added to this scene.
  16498. * @see BABYLON.Light
  16499. * @type {BABYLON.Light[]}
  16500. */
  16501. this.lights = new Array();
  16502. // Cameras
  16503. /** All of the cameras added to this scene. */
  16504. this.cameras = new Array();
  16505. /** All of the active cameras added to this scene. */
  16506. this.activeCameras = new Array();
  16507. // Meshes
  16508. /**
  16509. * All of the (abstract) meshes added to this scene.
  16510. * @see BABYLON.AbstractMesh
  16511. * @type {BABYLON.AbstractMesh[]}
  16512. */
  16513. this.meshes = new Array();
  16514. // Geometries
  16515. this._geometries = new Array();
  16516. this.materials = new Array();
  16517. this.multiMaterials = new Array();
  16518. // Textures
  16519. this._texturesEnabled = true;
  16520. this.textures = new Array();
  16521. // Particles
  16522. this.particlesEnabled = true;
  16523. this.particleSystems = new Array();
  16524. // Sprites
  16525. this.spritesEnabled = true;
  16526. this.spriteManagers = new Array();
  16527. // Layers
  16528. this.layers = new Array();
  16529. this.highlightLayers = new Array();
  16530. // Skeletons
  16531. this._skeletonsEnabled = true;
  16532. this.skeletons = new Array();
  16533. // Morph targets
  16534. this.morphTargetManagers = new Array();
  16535. // Lens flares
  16536. this.lensFlaresEnabled = true;
  16537. this.lensFlareSystems = new Array();
  16538. // Collisions
  16539. this.collisionsEnabled = true;
  16540. /** Defines the gravity applied to this scene */
  16541. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16542. // Postprocesses
  16543. this.postProcesses = new Array();
  16544. this.postProcessesEnabled = true;
  16545. // Customs render targets
  16546. this.renderTargetsEnabled = true;
  16547. this.dumpNextRenderTargets = false;
  16548. this.customRenderTargets = new Array();
  16549. // Imported meshes
  16550. this.importedMeshesFiles = new Array();
  16551. // Probes
  16552. this.probesEnabled = true;
  16553. this.reflectionProbes = new Array();
  16554. this._actionManagers = new Array();
  16555. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16556. // Procedural textures
  16557. this.proceduralTexturesEnabled = true;
  16558. this._proceduralTextures = new Array();
  16559. this.soundTracks = new Array();
  16560. this._audioEnabled = true;
  16561. this._headphone = false;
  16562. // Performance counters
  16563. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16564. this._totalLightsCounter = new BABYLON.PerfCounter();
  16565. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16566. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16567. this._totalVertices = new BABYLON.PerfCounter();
  16568. this._activeIndices = new BABYLON.PerfCounter();
  16569. this._activeParticles = new BABYLON.PerfCounter();
  16570. this._lastFrameDuration = new BABYLON.PerfCounter();
  16571. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16572. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16573. this._particlesDuration = new BABYLON.PerfCounter();
  16574. this._renderDuration = new BABYLON.PerfCounter();
  16575. this._spritesDuration = new BABYLON.PerfCounter();
  16576. this._activeBones = new BABYLON.PerfCounter();
  16577. this._animationTime = 0;
  16578. this.animationTimeScale = 1;
  16579. this._renderId = 0;
  16580. this._executeWhenReadyTimeoutId = -1;
  16581. this._intermediateRendering = false;
  16582. this._viewUpdateFlag = -1;
  16583. this._projectionUpdateFlag = -1;
  16584. this._toBeDisposed = new BABYLON.SmartArray(256);
  16585. this._pendingData = []; //ANY
  16586. this._activeMeshes = new BABYLON.SmartArray(256);
  16587. this._processedMaterials = new BABYLON.SmartArray(256);
  16588. this._renderTargets = new BABYLON.SmartArray(256);
  16589. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16590. this._activeSkeletons = new BABYLON.SmartArray(32);
  16591. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16592. this._activeAnimatables = new Array();
  16593. this._transformMatrix = BABYLON.Matrix.Zero();
  16594. this.requireLightSorting = false;
  16595. this._uniqueIdCounter = 0;
  16596. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16597. this._engine.scenes.push(this);
  16598. this._uid = null;
  16599. this._renderingManager = new BABYLON.RenderingManager(this);
  16600. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16601. if (BABYLON.OutlineRenderer) {
  16602. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16603. }
  16604. this.attachControl();
  16605. if (BABYLON.SoundTrack) {
  16606. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16607. }
  16608. //simplification queue
  16609. if (BABYLON.SimplificationQueue) {
  16610. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16611. }
  16612. //collision coordinator initialization. For now legacy per default.
  16613. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16614. // Uniform Buffer
  16615. this._createUbo();
  16616. // Default Image processing definition.
  16617. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16618. }
  16619. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16620. /** The fog is deactivated */
  16621. get: function () {
  16622. return Scene._FOGMODE_NONE;
  16623. },
  16624. enumerable: true,
  16625. configurable: true
  16626. });
  16627. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16628. /** The fog density is following an exponential function */
  16629. get: function () {
  16630. return Scene._FOGMODE_EXP;
  16631. },
  16632. enumerable: true,
  16633. configurable: true
  16634. });
  16635. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16636. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16637. get: function () {
  16638. return Scene._FOGMODE_EXP2;
  16639. },
  16640. enumerable: true,
  16641. configurable: true
  16642. });
  16643. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16644. /** The fog density is following a linear function. */
  16645. get: function () {
  16646. return Scene._FOGMODE_LINEAR;
  16647. },
  16648. enumerable: true,
  16649. configurable: true
  16650. });
  16651. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16652. /**
  16653. * Texture used in all pbr material as the reflection texture.
  16654. * As in the majority of the scene they are the same (exception for multi room and so on),
  16655. * this is easier to reference from here than from all the materials.
  16656. */
  16657. get: function () {
  16658. return this._environmentTexture;
  16659. },
  16660. /**
  16661. * Texture used in all pbr material as the reflection texture.
  16662. * As in the majority of the scene they are the same (exception for multi room and so on),
  16663. * this is easier to set here than in all the materials.
  16664. */
  16665. set: function (value) {
  16666. this._environmentTexture = value;
  16667. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16668. },
  16669. enumerable: true,
  16670. configurable: true
  16671. });
  16672. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16673. /**
  16674. * Default image processing configuration used either in the rendering
  16675. * Forward main pass or through the imageProcessingPostProcess if present.
  16676. * As in the majority of the scene they are the same (exception for multi camera),
  16677. * this is easier to reference from here than from all the materials and post process.
  16678. *
  16679. * No setter as we it is a shared configuration, you can set the values instead.
  16680. */
  16681. get: function () {
  16682. return this._imageProcessingConfiguration;
  16683. },
  16684. enumerable: true,
  16685. configurable: true
  16686. });
  16687. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16688. get: function () {
  16689. return this._forcePointsCloud;
  16690. },
  16691. set: function (value) {
  16692. if (this._forcePointsCloud === value) {
  16693. return;
  16694. }
  16695. this._forcePointsCloud = value;
  16696. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16697. },
  16698. enumerable: true,
  16699. configurable: true
  16700. });
  16701. Object.defineProperty(Scene.prototype, "onDispose", {
  16702. /** A function to be executed when this scene is disposed. */
  16703. set: function (callback) {
  16704. if (this._onDisposeObserver) {
  16705. this.onDisposeObservable.remove(this._onDisposeObserver);
  16706. }
  16707. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16708. },
  16709. enumerable: true,
  16710. configurable: true
  16711. });
  16712. Object.defineProperty(Scene.prototype, "beforeRender", {
  16713. /** A function to be executed before rendering this scene */
  16714. set: function (callback) {
  16715. if (this._onBeforeRenderObserver) {
  16716. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16717. }
  16718. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16719. },
  16720. enumerable: true,
  16721. configurable: true
  16722. });
  16723. Object.defineProperty(Scene.prototype, "afterRender", {
  16724. /** A function to be executed after rendering this scene */
  16725. set: function (callback) {
  16726. if (this._onAfterRenderObserver) {
  16727. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16728. }
  16729. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16730. },
  16731. enumerable: true,
  16732. configurable: true
  16733. });
  16734. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16735. set: function (callback) {
  16736. if (this._onBeforeCameraRenderObserver) {
  16737. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16738. }
  16739. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16740. },
  16741. enumerable: true,
  16742. configurable: true
  16743. });
  16744. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16745. set: function (callback) {
  16746. if (this._onAfterCameraRenderObserver) {
  16747. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16748. }
  16749. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16750. },
  16751. enumerable: true,
  16752. configurable: true
  16753. });
  16754. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16755. get: function () {
  16756. if (!this._gamepadManager) {
  16757. this._gamepadManager = new BABYLON.GamepadManager();
  16758. }
  16759. return this._gamepadManager;
  16760. },
  16761. enumerable: true,
  16762. configurable: true
  16763. });
  16764. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16765. get: function () {
  16766. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16767. },
  16768. enumerable: true,
  16769. configurable: true
  16770. });
  16771. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16772. get: function () {
  16773. return this._useRightHandedSystem;
  16774. },
  16775. set: function (value) {
  16776. if (this._useRightHandedSystem === value) {
  16777. return;
  16778. }
  16779. this._useRightHandedSystem = value;
  16780. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16781. },
  16782. enumerable: true,
  16783. configurable: true
  16784. });
  16785. Scene.prototype.setStepId = function (newStepId) {
  16786. this._currentStepId = newStepId;
  16787. };
  16788. ;
  16789. Scene.prototype.getStepId = function () {
  16790. return this._currentStepId;
  16791. };
  16792. ;
  16793. Scene.prototype.getInternalStep = function () {
  16794. return this._currentInternalStep;
  16795. };
  16796. ;
  16797. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16798. get: function () {
  16799. return this._fogEnabled;
  16800. },
  16801. /**
  16802. * is fog enabled on this scene.
  16803. */
  16804. set: function (value) {
  16805. if (this._fogEnabled === value) {
  16806. return;
  16807. }
  16808. this._fogEnabled = value;
  16809. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16810. },
  16811. enumerable: true,
  16812. configurable: true
  16813. });
  16814. Object.defineProperty(Scene.prototype, "fogMode", {
  16815. get: function () {
  16816. return this._fogMode;
  16817. },
  16818. set: function (value) {
  16819. if (this._fogMode === value) {
  16820. return;
  16821. }
  16822. this._fogMode = value;
  16823. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16824. },
  16825. enumerable: true,
  16826. configurable: true
  16827. });
  16828. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16829. get: function () {
  16830. return this._shadowsEnabled;
  16831. },
  16832. set: function (value) {
  16833. if (this._shadowsEnabled === value) {
  16834. return;
  16835. }
  16836. this._shadowsEnabled = value;
  16837. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16838. },
  16839. enumerable: true,
  16840. configurable: true
  16841. });
  16842. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16843. get: function () {
  16844. return this._lightsEnabled;
  16845. },
  16846. set: function (value) {
  16847. if (this._lightsEnabled === value) {
  16848. return;
  16849. }
  16850. this._lightsEnabled = value;
  16851. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16852. },
  16853. enumerable: true,
  16854. configurable: true
  16855. });
  16856. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16857. /** The default material used on meshes when no material is affected */
  16858. get: function () {
  16859. if (!this._defaultMaterial) {
  16860. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16861. }
  16862. return this._defaultMaterial;
  16863. },
  16864. /** The default material used on meshes when no material is affected */
  16865. set: function (value) {
  16866. this._defaultMaterial = value;
  16867. },
  16868. enumerable: true,
  16869. configurable: true
  16870. });
  16871. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16872. get: function () {
  16873. return this._texturesEnabled;
  16874. },
  16875. set: function (value) {
  16876. if (this._texturesEnabled === value) {
  16877. return;
  16878. }
  16879. this._texturesEnabled = value;
  16880. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16881. },
  16882. enumerable: true,
  16883. configurable: true
  16884. });
  16885. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16886. get: function () {
  16887. return this._skeletonsEnabled;
  16888. },
  16889. set: function (value) {
  16890. if (this._skeletonsEnabled === value) {
  16891. return;
  16892. }
  16893. this._skeletonsEnabled = value;
  16894. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16895. },
  16896. enumerable: true,
  16897. configurable: true
  16898. });
  16899. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16900. get: function () {
  16901. if (!this._postProcessRenderPipelineManager) {
  16902. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16903. }
  16904. return this._postProcessRenderPipelineManager;
  16905. },
  16906. enumerable: true,
  16907. configurable: true
  16908. });
  16909. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16910. get: function () {
  16911. return this._frustumPlanes;
  16912. },
  16913. enumerable: true,
  16914. configurable: true
  16915. });
  16916. Object.defineProperty(Scene.prototype, "debugLayer", {
  16917. // Properties
  16918. get: function () {
  16919. if (!this._debugLayer) {
  16920. this._debugLayer = new BABYLON.DebugLayer(this);
  16921. }
  16922. return this._debugLayer;
  16923. },
  16924. enumerable: true,
  16925. configurable: true
  16926. });
  16927. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16928. get: function () {
  16929. return this._workerCollisions;
  16930. },
  16931. set: function (enabled) {
  16932. if (!BABYLON.CollisionCoordinatorLegacy) {
  16933. return;
  16934. }
  16935. enabled = (enabled && !!Worker);
  16936. this._workerCollisions = enabled;
  16937. if (this.collisionCoordinator) {
  16938. this.collisionCoordinator.destroy();
  16939. }
  16940. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16941. this.collisionCoordinator.init(this);
  16942. },
  16943. enumerable: true,
  16944. configurable: true
  16945. });
  16946. Object.defineProperty(Scene.prototype, "selectionOctree", {
  16947. get: function () {
  16948. return this._selectionOctree;
  16949. },
  16950. enumerable: true,
  16951. configurable: true
  16952. });
  16953. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16954. /**
  16955. * The mesh that is currently under the pointer.
  16956. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16957. */
  16958. get: function () {
  16959. return this._pointerOverMesh;
  16960. },
  16961. enumerable: true,
  16962. configurable: true
  16963. });
  16964. Object.defineProperty(Scene.prototype, "pointerX", {
  16965. /**
  16966. * Current on-screen X position of the pointer
  16967. * @return {number} X position of the pointer
  16968. */
  16969. get: function () {
  16970. return this._pointerX;
  16971. },
  16972. enumerable: true,
  16973. configurable: true
  16974. });
  16975. Object.defineProperty(Scene.prototype, "pointerY", {
  16976. /**
  16977. * Current on-screen Y position of the pointer
  16978. * @return {number} Y position of the pointer
  16979. */
  16980. get: function () {
  16981. return this._pointerY;
  16982. },
  16983. enumerable: true,
  16984. configurable: true
  16985. });
  16986. Scene.prototype.getCachedMaterial = function () {
  16987. return this._cachedMaterial;
  16988. };
  16989. Scene.prototype.getCachedEffect = function () {
  16990. return this._cachedEffect;
  16991. };
  16992. Scene.prototype.getCachedVisibility = function () {
  16993. return this._cachedVisibility;
  16994. };
  16995. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  16996. if (visibility === void 0) { visibility = 1; }
  16997. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16998. };
  16999. Scene.prototype.getBoundingBoxRenderer = function () {
  17000. if (!this._boundingBoxRenderer) {
  17001. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17002. }
  17003. return this._boundingBoxRenderer;
  17004. };
  17005. Scene.prototype.getOutlineRenderer = function () {
  17006. return this._outlineRenderer;
  17007. };
  17008. Scene.prototype.getEngine = function () {
  17009. return this._engine;
  17010. };
  17011. Scene.prototype.getTotalVertices = function () {
  17012. return this._totalVertices.current;
  17013. };
  17014. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17015. get: function () {
  17016. return this._totalVertices;
  17017. },
  17018. enumerable: true,
  17019. configurable: true
  17020. });
  17021. Scene.prototype.getActiveIndices = function () {
  17022. return this._activeIndices.current;
  17023. };
  17024. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17025. get: function () {
  17026. return this._activeIndices;
  17027. },
  17028. enumerable: true,
  17029. configurable: true
  17030. });
  17031. Scene.prototype.getActiveParticles = function () {
  17032. return this._activeParticles.current;
  17033. };
  17034. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17035. get: function () {
  17036. return this._activeParticles;
  17037. },
  17038. enumerable: true,
  17039. configurable: true
  17040. });
  17041. Scene.prototype.getActiveBones = function () {
  17042. return this._activeBones.current;
  17043. };
  17044. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17045. get: function () {
  17046. return this._activeBones;
  17047. },
  17048. enumerable: true,
  17049. configurable: true
  17050. });
  17051. // Stats
  17052. Scene.prototype.getLastFrameDuration = function () {
  17053. return this._lastFrameDuration.current;
  17054. };
  17055. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17056. get: function () {
  17057. return this._lastFrameDuration;
  17058. },
  17059. enumerable: true,
  17060. configurable: true
  17061. });
  17062. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17063. return this._evaluateActiveMeshesDuration.current;
  17064. };
  17065. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17066. get: function () {
  17067. return this._evaluateActiveMeshesDuration;
  17068. },
  17069. enumerable: true,
  17070. configurable: true
  17071. });
  17072. Scene.prototype.getActiveMeshes = function () {
  17073. return this._activeMeshes;
  17074. };
  17075. Scene.prototype.getRenderTargetsDuration = function () {
  17076. return this._renderTargetsDuration.current;
  17077. };
  17078. Scene.prototype.getRenderDuration = function () {
  17079. return this._renderDuration.current;
  17080. };
  17081. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17082. get: function () {
  17083. return this._renderDuration;
  17084. },
  17085. enumerable: true,
  17086. configurable: true
  17087. });
  17088. Scene.prototype.getParticlesDuration = function () {
  17089. return this._particlesDuration.current;
  17090. };
  17091. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17092. get: function () {
  17093. return this._particlesDuration;
  17094. },
  17095. enumerable: true,
  17096. configurable: true
  17097. });
  17098. Scene.prototype.getSpritesDuration = function () {
  17099. return this._spritesDuration.current;
  17100. };
  17101. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17102. get: function () {
  17103. return this._spritesDuration;
  17104. },
  17105. enumerable: true,
  17106. configurable: true
  17107. });
  17108. Scene.prototype.getAnimationRatio = function () {
  17109. return this._animationRatio;
  17110. };
  17111. Scene.prototype.getRenderId = function () {
  17112. return this._renderId;
  17113. };
  17114. Scene.prototype.incrementRenderId = function () {
  17115. this._renderId++;
  17116. };
  17117. Scene.prototype._updatePointerPosition = function (evt) {
  17118. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17119. this._pointerX = evt.clientX - canvasRect.left;
  17120. this._pointerY = evt.clientY - canvasRect.top;
  17121. this._unTranslatedPointerX = this._pointerX;
  17122. this._unTranslatedPointerY = this._pointerY;
  17123. };
  17124. Scene.prototype._createUbo = function () {
  17125. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17126. this._sceneUbo.addUniform("viewProjection", 16);
  17127. this._sceneUbo.addUniform("view", 16);
  17128. };
  17129. // Pointers handling
  17130. /**
  17131. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17132. * @param attachUp defines if you want to attach events to pointerup
  17133. * @param attachDown defines if you want to attach events to pointerdown
  17134. * @param attachMove defines if you want to attach events to pointermove
  17135. */
  17136. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17137. var _this = this;
  17138. if (attachUp === void 0) { attachUp = true; }
  17139. if (attachDown === void 0) { attachDown = true; }
  17140. if (attachMove === void 0) { attachMove = true; }
  17141. this._initActionManager = function (act, clickInfo) {
  17142. if (!_this._meshPickProceed) {
  17143. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17144. _this._currentPickResult = pickResult;
  17145. if (pickResult) {
  17146. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17147. }
  17148. _this._meshPickProceed = true;
  17149. }
  17150. return act;
  17151. };
  17152. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17153. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17154. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17155. btn !== _this._previousButtonPressed) {
  17156. _this._doubleClickOccured = false;
  17157. clickInfo.singleClick = true;
  17158. clickInfo.ignore = false;
  17159. cb(clickInfo, _this._currentPickResult);
  17160. }
  17161. };
  17162. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17163. var clickInfo = new ClickInfo();
  17164. _this._currentPickResult = null;
  17165. var act;
  17166. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  17167. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  17168. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17169. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17170. act = _this._initActionManager(act, clickInfo);
  17171. if (act)
  17172. checkPicking = act.hasPickTriggers;
  17173. }
  17174. if (checkPicking) {
  17175. var btn = evt.button;
  17176. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17177. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17178. if (!clickInfo.hasSwiped) {
  17179. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17180. if (!checkSingleClickImmediately) {
  17181. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  17182. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17183. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17184. act = _this._initActionManager(act, clickInfo);
  17185. if (act)
  17186. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17187. }
  17188. }
  17189. if (checkSingleClickImmediately) {
  17190. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17191. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17192. btn !== _this._previousButtonPressed) {
  17193. clickInfo.singleClick = true;
  17194. cb(clickInfo, _this._currentPickResult);
  17195. }
  17196. }
  17197. else {
  17198. // wait that no double click has been raised during the double click delay
  17199. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17200. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17201. }
  17202. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  17203. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17204. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17205. act = _this._initActionManager(act, clickInfo);
  17206. if (act)
  17207. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17208. }
  17209. if (checkDoubleClick) {
  17210. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17211. if (btn === _this._previousButtonPressed &&
  17212. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17213. !_this._doubleClickOccured) {
  17214. // pointer has not moved for 2 clicks, it's a double click
  17215. if (!clickInfo.hasSwiped &&
  17216. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17217. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17218. _this._previousStartingPointerTime = 0;
  17219. _this._doubleClickOccured = true;
  17220. clickInfo.doubleClick = true;
  17221. clickInfo.ignore = false;
  17222. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17223. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17224. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17225. cb(clickInfo, _this._currentPickResult);
  17226. }
  17227. else {
  17228. _this._doubleClickOccured = false;
  17229. _this._previousStartingPointerTime = _this._startingPointerTime;
  17230. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17231. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17232. _this._previousButtonPressed = btn;
  17233. _this._previousHasSwiped = clickInfo.hasSwiped;
  17234. if (Scene.ExclusiveDoubleClickMode) {
  17235. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17236. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17237. }
  17238. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17239. cb(clickInfo, _this._previousPickResult);
  17240. }
  17241. else {
  17242. cb(clickInfo, _this._currentPickResult);
  17243. }
  17244. }
  17245. }
  17246. else {
  17247. _this._doubleClickOccured = false;
  17248. _this._previousStartingPointerTime = _this._startingPointerTime;
  17249. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17250. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17251. _this._previousButtonPressed = btn;
  17252. _this._previousHasSwiped = clickInfo.hasSwiped;
  17253. }
  17254. }
  17255. }
  17256. }
  17257. clickInfo.ignore = true;
  17258. cb(clickInfo, _this._currentPickResult);
  17259. };
  17260. var spritePredicate = function (sprite) {
  17261. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17262. };
  17263. this._onPointerMove = function (evt) {
  17264. _this._updatePointerPosition(evt);
  17265. // PreObservable support
  17266. if (_this.onPrePointerObservable.hasObservers()) {
  17267. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17268. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17269. _this.onPrePointerObservable.notifyObservers(pi, type);
  17270. if (pi.skipOnPointerObservable) {
  17271. return;
  17272. }
  17273. }
  17274. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17275. return;
  17276. }
  17277. var canvas = _this._engine.getRenderingCanvas();
  17278. if (!_this.pointerMovePredicate) {
  17279. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17280. }
  17281. // Meshes
  17282. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17283. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17284. _this.setPointerOverSprite(null);
  17285. _this.setPointerOverMesh(pickResult.pickedMesh);
  17286. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17287. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17288. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17289. }
  17290. else {
  17291. canvas.style.cursor = _this.hoverCursor;
  17292. }
  17293. }
  17294. else {
  17295. canvas.style.cursor = _this.defaultCursor;
  17296. }
  17297. }
  17298. else {
  17299. _this.setPointerOverMesh(null);
  17300. // Sprites
  17301. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17302. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17303. _this.setPointerOverSprite(pickResult.pickedSprite);
  17304. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17305. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17306. }
  17307. else {
  17308. canvas.style.cursor = _this.hoverCursor;
  17309. }
  17310. }
  17311. else {
  17312. _this.setPointerOverSprite(null);
  17313. // Restore pointer
  17314. canvas.style.cursor = _this.defaultCursor;
  17315. }
  17316. }
  17317. if (_this.onPointerMove) {
  17318. _this.onPointerMove(evt, pickResult);
  17319. }
  17320. if (_this.onPointerObservable.hasObservers()) {
  17321. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17322. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17323. _this.onPointerObservable.notifyObservers(pi, type);
  17324. }
  17325. };
  17326. this._onPointerDown = function (evt) {
  17327. _this._isButtonPressed = true;
  17328. _this._pickedDownMesh = null;
  17329. _this._meshPickProceed = false;
  17330. _this._updatePointerPosition(evt);
  17331. // PreObservable support
  17332. if (_this.onPrePointerObservable.hasObservers()) {
  17333. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17334. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17335. _this.onPrePointerObservable.notifyObservers(pi, type);
  17336. if (pi.skipOnPointerObservable) {
  17337. return;
  17338. }
  17339. }
  17340. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17341. return;
  17342. }
  17343. _this._startingPointerPosition.x = _this._pointerX;
  17344. _this._startingPointerPosition.y = _this._pointerY;
  17345. _this._startingPointerTime = new Date().getTime();
  17346. if (!_this.pointerDownPredicate) {
  17347. _this.pointerDownPredicate = function (mesh) {
  17348. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17349. };
  17350. }
  17351. // Meshes
  17352. _this._pickedDownMesh = null;
  17353. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17354. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17355. _this._pickedDownMesh = pickResult.pickedMesh;
  17356. var actionManager = pickResult.pickedMesh.actionManager;
  17357. if (actionManager) {
  17358. if (actionManager.hasPickTriggers) {
  17359. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17360. switch (evt.button) {
  17361. case 0:
  17362. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17363. break;
  17364. case 1:
  17365. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17366. break;
  17367. case 2:
  17368. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17369. break;
  17370. }
  17371. }
  17372. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17373. window.setTimeout((function () {
  17374. var _this = this;
  17375. 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);
  17376. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17377. if (this._isButtonPressed &&
  17378. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17379. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17380. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17381. this._startingPointerTime = 0;
  17382. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17383. }
  17384. }
  17385. }).bind(_this), Scene.LongPressDelay);
  17386. }
  17387. }
  17388. }
  17389. if (_this.onPointerDown) {
  17390. _this.onPointerDown(evt, pickResult);
  17391. }
  17392. if (_this.onPointerObservable.hasObservers()) {
  17393. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17394. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17395. _this.onPointerObservable.notifyObservers(pi, type);
  17396. }
  17397. // Sprites
  17398. _this._pickedDownSprite = null;
  17399. if (_this.spriteManagers.length > 0) {
  17400. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17401. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17402. if (pickResult.pickedSprite.actionManager) {
  17403. _this._pickedDownSprite = pickResult.pickedSprite;
  17404. switch (evt.button) {
  17405. case 0:
  17406. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17407. break;
  17408. case 1:
  17409. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17410. break;
  17411. case 2:
  17412. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17413. break;
  17414. }
  17415. if (pickResult.pickedSprite.actionManager) {
  17416. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17417. }
  17418. }
  17419. }
  17420. }
  17421. };
  17422. this._onPointerUp = function (evt) {
  17423. _this._isButtonPressed = false;
  17424. _this._pickedUpMesh = null;
  17425. _this._meshPickProceed = false;
  17426. _this._updatePointerPosition(evt);
  17427. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17428. // PreObservable support
  17429. if (this.onPrePointerObservable.hasObservers()) {
  17430. if (!clickInfo.ignore) {
  17431. if (!clickInfo.hasSwiped) {
  17432. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17433. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17434. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17435. this.onPrePointerObservable.notifyObservers(pi, type);
  17436. if (pi.skipOnPointerObservable) {
  17437. return;
  17438. }
  17439. }
  17440. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17441. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17442. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17443. this.onPrePointerObservable.notifyObservers(pi, type);
  17444. if (pi.skipOnPointerObservable) {
  17445. return;
  17446. }
  17447. }
  17448. }
  17449. }
  17450. else {
  17451. var type = BABYLON.PointerEventTypes.POINTERUP;
  17452. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17453. this.onPrePointerObservable.notifyObservers(pi, type);
  17454. if (pi.skipOnPointerObservable) {
  17455. return;
  17456. }
  17457. }
  17458. }
  17459. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17460. return;
  17461. }
  17462. if (!this.pointerUpPredicate) {
  17463. this.pointerUpPredicate = function (mesh) {
  17464. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17465. };
  17466. }
  17467. // Meshes
  17468. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17469. this._initActionManager(null, clickInfo);
  17470. }
  17471. if (!pickResult) {
  17472. pickResult = this._currentPickResult;
  17473. }
  17474. if (pickResult && pickResult && pickResult.pickedMesh) {
  17475. this._pickedUpMesh = pickResult.pickedMesh;
  17476. if (this._pickedDownMesh === this._pickedUpMesh) {
  17477. if (this.onPointerPick) {
  17478. this.onPointerPick(evt, pickResult);
  17479. }
  17480. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17481. var type = BABYLON.PointerEventTypes.POINTERPICK;
  17482. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17483. this.onPointerObservable.notifyObservers(pi, type);
  17484. }
  17485. }
  17486. if (pickResult.pickedMesh.actionManager) {
  17487. if (clickInfo.ignore) {
  17488. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17489. }
  17490. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17491. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17492. }
  17493. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17494. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17495. }
  17496. }
  17497. }
  17498. if (this._pickedDownMesh &&
  17499. this._pickedDownMesh.actionManager &&
  17500. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17501. this._pickedDownMesh !== this._pickedUpMesh) {
  17502. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17503. }
  17504. if (this.onPointerUp) {
  17505. this.onPointerUp(evt, pickResult);
  17506. }
  17507. if (this.onPointerObservable.hasObservers()) {
  17508. if (!clickInfo.ignore) {
  17509. if (!clickInfo.hasSwiped) {
  17510. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17511. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17512. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17513. this.onPointerObservable.notifyObservers(pi, type);
  17514. }
  17515. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17516. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17517. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17518. this.onPointerObservable.notifyObservers(pi, type);
  17519. }
  17520. }
  17521. }
  17522. else {
  17523. var type = BABYLON.PointerEventTypes.POINTERUP;
  17524. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17525. this.onPointerObservable.notifyObservers(pi, type);
  17526. }
  17527. }
  17528. // Sprites
  17529. if (this.spriteManagers.length > 0) {
  17530. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  17531. if (pickResult.hit && pickResult.pickedSprite) {
  17532. if (pickResult.pickedSprite.actionManager) {
  17533. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17534. if (pickResult.pickedSprite.actionManager) {
  17535. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17536. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17537. }
  17538. }
  17539. }
  17540. }
  17541. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17542. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17543. }
  17544. }
  17545. this._previousPickResult = this._currentPickResult;
  17546. }).bind(_this));
  17547. };
  17548. this._onKeyDown = function (evt) {
  17549. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  17550. if (_this.onPreKeyboardObservable.hasObservers()) {
  17551. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17552. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17553. if (pi.skipOnPointerObservable) {
  17554. return;
  17555. }
  17556. }
  17557. if (_this.onKeyboardObservable.hasObservers()) {
  17558. var pi = new BABYLON.KeyboardInfo(type, evt);
  17559. _this.onKeyboardObservable.notifyObservers(pi, type);
  17560. }
  17561. if (_this.actionManager) {
  17562. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17563. }
  17564. };
  17565. this._onKeyUp = function (evt) {
  17566. var type = BABYLON.KeyboardEventTypes.KEYUP;
  17567. if (_this.onPreKeyboardObservable.hasObservers()) {
  17568. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17569. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17570. if (pi.skipOnPointerObservable) {
  17571. return;
  17572. }
  17573. }
  17574. if (_this.onKeyboardObservable.hasObservers()) {
  17575. var pi = new BABYLON.KeyboardInfo(type, evt);
  17576. _this.onKeyboardObservable.notifyObservers(pi, type);
  17577. }
  17578. if (_this.actionManager) {
  17579. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17580. }
  17581. };
  17582. var engine = this.getEngine();
  17583. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  17584. canvas.addEventListener("keydown", _this._onKeyDown, false);
  17585. canvas.addEventListener("keyup", _this._onKeyUp, false);
  17586. });
  17587. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  17588. canvas.removeEventListener("keydown", _this._onKeyDown);
  17589. canvas.removeEventListener("keyup", _this._onKeyUp);
  17590. });
  17591. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17592. var canvas = this._engine.getRenderingCanvas();
  17593. if (attachMove) {
  17594. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17595. // Wheel
  17596. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17597. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17598. }
  17599. if (attachDown) {
  17600. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17601. }
  17602. if (attachUp) {
  17603. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17604. }
  17605. canvas.tabIndex = 1;
  17606. };
  17607. Scene.prototype.detachControl = function () {
  17608. var engine = this.getEngine();
  17609. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17610. var canvas = engine.getRenderingCanvas();
  17611. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17612. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17613. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17614. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  17615. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  17616. // Wheel
  17617. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17618. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17619. // Keyboard
  17620. canvas.removeEventListener("keydown", this._onKeyDown);
  17621. canvas.removeEventListener("keyup", this._onKeyUp);
  17622. // Observables
  17623. this.onKeyboardObservable.clear();
  17624. this.onPreKeyboardObservable.clear();
  17625. this.onPointerObservable.clear();
  17626. this.onPrePointerObservable.clear();
  17627. };
  17628. // Ready
  17629. Scene.prototype.isReady = function () {
  17630. if (this._pendingData.length > 0) {
  17631. return false;
  17632. }
  17633. var index;
  17634. // Geometries
  17635. for (index = 0; index < this._geometries.length; index++) {
  17636. var geometry = this._geometries[index];
  17637. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17638. return false;
  17639. }
  17640. }
  17641. // Meshes
  17642. for (index = 0; index < this.meshes.length; index++) {
  17643. var mesh = this.meshes[index];
  17644. if (!mesh.isEnabled()) {
  17645. continue;
  17646. }
  17647. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17648. continue;
  17649. }
  17650. if (!mesh.isReady()) {
  17651. return false;
  17652. }
  17653. var mat = mesh.material;
  17654. if (mat) {
  17655. if (!mat.isReady(mesh)) {
  17656. return false;
  17657. }
  17658. }
  17659. }
  17660. return true;
  17661. };
  17662. Scene.prototype.resetCachedMaterial = function () {
  17663. this._cachedMaterial = null;
  17664. this._cachedEffect = null;
  17665. this._cachedVisibility = null;
  17666. };
  17667. Scene.prototype.registerBeforeRender = function (func) {
  17668. this.onBeforeRenderObservable.add(func);
  17669. };
  17670. Scene.prototype.unregisterBeforeRender = function (func) {
  17671. this.onBeforeRenderObservable.removeCallback(func);
  17672. };
  17673. Scene.prototype.registerAfterRender = function (func) {
  17674. this.onAfterRenderObservable.add(func);
  17675. };
  17676. Scene.prototype.unregisterAfterRender = function (func) {
  17677. this.onAfterRenderObservable.removeCallback(func);
  17678. };
  17679. Scene.prototype._addPendingData = function (data) {
  17680. this._pendingData.push(data);
  17681. };
  17682. Scene.prototype._removePendingData = function (data) {
  17683. var index = this._pendingData.indexOf(data);
  17684. if (index !== -1) {
  17685. this._pendingData.splice(index, 1);
  17686. }
  17687. };
  17688. Scene.prototype.getWaitingItemsCount = function () {
  17689. return this._pendingData.length;
  17690. };
  17691. /**
  17692. * Registers a function to be executed when the scene is ready.
  17693. * @param {Function} func - the function to be executed.
  17694. */
  17695. Scene.prototype.executeWhenReady = function (func) {
  17696. var _this = this;
  17697. this.onReadyObservable.add(func);
  17698. if (this._executeWhenReadyTimeoutId !== -1) {
  17699. return;
  17700. }
  17701. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17702. _this._checkIsReady();
  17703. }, 150);
  17704. };
  17705. Scene.prototype._checkIsReady = function () {
  17706. var _this = this;
  17707. if (this.isReady()) {
  17708. this.onReadyObservable.notifyObservers(this);
  17709. this.onReadyObservable.clear();
  17710. this._executeWhenReadyTimeoutId = -1;
  17711. return;
  17712. }
  17713. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17714. _this._checkIsReady();
  17715. }, 150);
  17716. };
  17717. // Animations
  17718. /**
  17719. * Will start the animation sequence of a given target
  17720. * @param target - the target
  17721. * @param {number} from - from which frame should animation start
  17722. * @param {number} to - till which frame should animation run.
  17723. * @param {boolean} [loop] - should the animation loop
  17724. * @param {number} [speedRatio] - the speed in which to run the animation
  17725. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17726. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17727. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17728. * See BABYLON.Animatable
  17729. */
  17730. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17731. if (speedRatio === void 0) { speedRatio = 1.0; }
  17732. if (from > to && speedRatio > 0) {
  17733. speedRatio *= -1;
  17734. }
  17735. this.stopAnimation(target);
  17736. if (!animatable) {
  17737. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17738. }
  17739. // Local animations
  17740. if (target.animations) {
  17741. animatable.appendAnimations(target, target.animations);
  17742. }
  17743. // Children animations
  17744. if (target.getAnimatables) {
  17745. var animatables = target.getAnimatables();
  17746. for (var index = 0; index < animatables.length; index++) {
  17747. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17748. }
  17749. }
  17750. animatable.reset();
  17751. return animatable;
  17752. };
  17753. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17754. if (speedRatio === undefined) {
  17755. speedRatio = 1.0;
  17756. }
  17757. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17758. return animatable;
  17759. };
  17760. Scene.prototype.getAnimatableByTarget = function (target) {
  17761. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17762. if (this._activeAnimatables[index].target === target) {
  17763. return this._activeAnimatables[index];
  17764. }
  17765. }
  17766. return null;
  17767. };
  17768. Object.defineProperty(Scene.prototype, "Animatables", {
  17769. get: function () {
  17770. return this._activeAnimatables;
  17771. },
  17772. enumerable: true,
  17773. configurable: true
  17774. });
  17775. /**
  17776. * Will stop the animation of the given target
  17777. * @param target - the target
  17778. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17779. * @see beginAnimation
  17780. */
  17781. Scene.prototype.stopAnimation = function (target, animationName) {
  17782. var animatable = this.getAnimatableByTarget(target);
  17783. if (animatable) {
  17784. animatable.stop(animationName);
  17785. }
  17786. };
  17787. Scene.prototype._animate = function () {
  17788. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17789. return;
  17790. }
  17791. // Getting time
  17792. var now = BABYLON.Tools.Now;
  17793. if (!this._animationTimeLast) {
  17794. if (this._pendingData.length > 0) {
  17795. return;
  17796. }
  17797. this._animationTimeLast = now;
  17798. }
  17799. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17800. this._animationTime += deltaTime;
  17801. this._animationTimeLast = now;
  17802. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17803. this._activeAnimatables[index]._animate(this._animationTime);
  17804. }
  17805. };
  17806. // Matrix
  17807. Scene.prototype.getViewMatrix = function () {
  17808. return this._viewMatrix;
  17809. };
  17810. Scene.prototype.getProjectionMatrix = function () {
  17811. return this._projectionMatrix;
  17812. };
  17813. Scene.prototype.getTransformMatrix = function () {
  17814. return this._transformMatrix;
  17815. };
  17816. Scene.prototype.setTransformMatrix = function (view, projection) {
  17817. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17818. return;
  17819. }
  17820. this._viewUpdateFlag = view.updateFlag;
  17821. this._projectionUpdateFlag = projection.updateFlag;
  17822. this._viewMatrix = view;
  17823. this._projectionMatrix = projection;
  17824. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17825. // Update frustum
  17826. if (!this._frustumPlanes) {
  17827. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17828. }
  17829. else {
  17830. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17831. }
  17832. if (this._sceneUbo.useUbo) {
  17833. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17834. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17835. this._sceneUbo.update();
  17836. }
  17837. };
  17838. Scene.prototype.getSceneUniformBuffer = function () {
  17839. return this._sceneUbo;
  17840. };
  17841. // Methods
  17842. Scene.prototype.getUniqueId = function () {
  17843. var result = this._uniqueIdCounter;
  17844. this._uniqueIdCounter++;
  17845. return result;
  17846. };
  17847. Scene.prototype.addMesh = function (newMesh) {
  17848. newMesh.uniqueId = this.getUniqueId();
  17849. var position = this.meshes.push(newMesh);
  17850. //notify the collision coordinator
  17851. if (this.collisionCoordinator) {
  17852. this.collisionCoordinator.onMeshAdded(newMesh);
  17853. }
  17854. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17855. };
  17856. Scene.prototype.removeMesh = function (toRemove) {
  17857. var index = this.meshes.indexOf(toRemove);
  17858. if (index !== -1) {
  17859. // Remove from the scene if mesh found
  17860. this.meshes.splice(index, 1);
  17861. }
  17862. //notify the collision coordinator
  17863. if (this.collisionCoordinator) {
  17864. this.collisionCoordinator.onMeshRemoved(toRemove);
  17865. }
  17866. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17867. return index;
  17868. };
  17869. Scene.prototype.removeSkeleton = function (toRemove) {
  17870. var index = this.skeletons.indexOf(toRemove);
  17871. if (index !== -1) {
  17872. // Remove from the scene if found
  17873. this.skeletons.splice(index, 1);
  17874. }
  17875. return index;
  17876. };
  17877. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17878. var index = this.morphTargetManagers.indexOf(toRemove);
  17879. if (index !== -1) {
  17880. // Remove from the scene if found
  17881. this.morphTargetManagers.splice(index, 1);
  17882. }
  17883. return index;
  17884. };
  17885. Scene.prototype.removeLight = function (toRemove) {
  17886. var index = this.lights.indexOf(toRemove);
  17887. if (index !== -1) {
  17888. // Remove from the scene if mesh found
  17889. this.lights.splice(index, 1);
  17890. this.sortLightsByPriority();
  17891. }
  17892. this.onLightRemovedObservable.notifyObservers(toRemove);
  17893. return index;
  17894. };
  17895. Scene.prototype.removeCamera = function (toRemove) {
  17896. var index = this.cameras.indexOf(toRemove);
  17897. if (index !== -1) {
  17898. // Remove from the scene if mesh found
  17899. this.cameras.splice(index, 1);
  17900. }
  17901. // Remove from activeCameras
  17902. var index2 = this.activeCameras.indexOf(toRemove);
  17903. if (index2 !== -1) {
  17904. // Remove from the scene if mesh found
  17905. this.activeCameras.splice(index2, 1);
  17906. }
  17907. // Reset the activeCamera
  17908. if (this.activeCamera === toRemove) {
  17909. if (this.cameras.length > 0) {
  17910. this.activeCamera = this.cameras[0];
  17911. }
  17912. else {
  17913. this.activeCamera = null;
  17914. }
  17915. }
  17916. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17917. return index;
  17918. };
  17919. Scene.prototype.addLight = function (newLight) {
  17920. newLight.uniqueId = this.getUniqueId();
  17921. this.lights.push(newLight);
  17922. this.sortLightsByPriority();
  17923. this.onNewLightAddedObservable.notifyObservers(newLight);
  17924. };
  17925. Scene.prototype.sortLightsByPriority = function () {
  17926. if (this.requireLightSorting) {
  17927. this.lights.sort(BABYLON.Light.compareLightsPriority);
  17928. }
  17929. };
  17930. Scene.prototype.addCamera = function (newCamera) {
  17931. newCamera.uniqueId = this.getUniqueId();
  17932. var position = this.cameras.push(newCamera);
  17933. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17934. };
  17935. /**
  17936. * Switch active camera
  17937. * @param {Camera} newCamera - new active camera
  17938. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17939. */
  17940. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17941. if (attachControl === void 0) { attachControl = true; }
  17942. var canvas = this._engine.getRenderingCanvas();
  17943. this.activeCamera.detachControl(canvas);
  17944. this.activeCamera = newCamera;
  17945. if (attachControl) {
  17946. newCamera.attachControl(canvas);
  17947. }
  17948. };
  17949. /**
  17950. * sets the active camera of the scene using its ID
  17951. * @param {string} id - the camera's ID
  17952. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17953. * @see activeCamera
  17954. */
  17955. Scene.prototype.setActiveCameraByID = function (id) {
  17956. var camera = this.getCameraByID(id);
  17957. if (camera) {
  17958. this.activeCamera = camera;
  17959. return camera;
  17960. }
  17961. return null;
  17962. };
  17963. /**
  17964. * sets the active camera of the scene using its name
  17965. * @param {string} name - the camera's name
  17966. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17967. * @see activeCamera
  17968. */
  17969. Scene.prototype.setActiveCameraByName = function (name) {
  17970. var camera = this.getCameraByName(name);
  17971. if (camera) {
  17972. this.activeCamera = camera;
  17973. return camera;
  17974. }
  17975. return null;
  17976. };
  17977. /**
  17978. * get a material using its id
  17979. * @param {string} the material's ID
  17980. * @return {BABYLON.Material|null} the material or null if none found.
  17981. */
  17982. Scene.prototype.getMaterialByID = function (id) {
  17983. for (var index = 0; index < this.materials.length; index++) {
  17984. if (this.materials[index].id === id) {
  17985. return this.materials[index];
  17986. }
  17987. }
  17988. return null;
  17989. };
  17990. /**
  17991. * get a material using its name
  17992. * @param {string} the material's name
  17993. * @return {BABYLON.Material|null} the material or null if none found.
  17994. */
  17995. Scene.prototype.getMaterialByName = function (name) {
  17996. for (var index = 0; index < this.materials.length; index++) {
  17997. if (this.materials[index].name === name) {
  17998. return this.materials[index];
  17999. }
  18000. }
  18001. return null;
  18002. };
  18003. Scene.prototype.getLensFlareSystemByName = function (name) {
  18004. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18005. if (this.lensFlareSystems[index].name === name) {
  18006. return this.lensFlareSystems[index];
  18007. }
  18008. }
  18009. return null;
  18010. };
  18011. Scene.prototype.getLensFlareSystemByID = function (id) {
  18012. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18013. if (this.lensFlareSystems[index].id === id) {
  18014. return this.lensFlareSystems[index];
  18015. }
  18016. }
  18017. return null;
  18018. };
  18019. Scene.prototype.getCameraByID = function (id) {
  18020. for (var index = 0; index < this.cameras.length; index++) {
  18021. if (this.cameras[index].id === id) {
  18022. return this.cameras[index];
  18023. }
  18024. }
  18025. return null;
  18026. };
  18027. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18028. for (var index = 0; index < this.cameras.length; index++) {
  18029. if (this.cameras[index].uniqueId === uniqueId) {
  18030. return this.cameras[index];
  18031. }
  18032. }
  18033. return null;
  18034. };
  18035. /**
  18036. * get a camera using its name
  18037. * @param {string} the camera's name
  18038. * @return {BABYLON.Camera|null} the camera or null if none found.
  18039. */
  18040. Scene.prototype.getCameraByName = function (name) {
  18041. for (var index = 0; index < this.cameras.length; index++) {
  18042. if (this.cameras[index].name === name) {
  18043. return this.cameras[index];
  18044. }
  18045. }
  18046. return null;
  18047. };
  18048. /**
  18049. * get a bone using its id
  18050. * @param {string} the bone's id
  18051. * @return {BABYLON.Bone|null} the bone or null if not found
  18052. */
  18053. Scene.prototype.getBoneByID = function (id) {
  18054. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18055. var skeleton = this.skeletons[skeletonIndex];
  18056. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18057. if (skeleton.bones[boneIndex].id === id) {
  18058. return skeleton.bones[boneIndex];
  18059. }
  18060. }
  18061. }
  18062. return null;
  18063. };
  18064. /**
  18065. * get a bone using its id
  18066. * @param {string} the bone's name
  18067. * @return {BABYLON.Bone|null} the bone or null if not found
  18068. */
  18069. Scene.prototype.getBoneByName = function (name) {
  18070. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18071. var skeleton = this.skeletons[skeletonIndex];
  18072. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18073. if (skeleton.bones[boneIndex].name === name) {
  18074. return skeleton.bones[boneIndex];
  18075. }
  18076. }
  18077. }
  18078. return null;
  18079. };
  18080. /**
  18081. * get a light node using its name
  18082. * @param {string} the light's name
  18083. * @return {BABYLON.Light|null} the light or null if none found.
  18084. */
  18085. Scene.prototype.getLightByName = function (name) {
  18086. for (var index = 0; index < this.lights.length; index++) {
  18087. if (this.lights[index].name === name) {
  18088. return this.lights[index];
  18089. }
  18090. }
  18091. return null;
  18092. };
  18093. /**
  18094. * get a light node using its ID
  18095. * @param {string} the light's id
  18096. * @return {BABYLON.Light|null} the light or null if none found.
  18097. */
  18098. Scene.prototype.getLightByID = function (id) {
  18099. for (var index = 0; index < this.lights.length; index++) {
  18100. if (this.lights[index].id === id) {
  18101. return this.lights[index];
  18102. }
  18103. }
  18104. return null;
  18105. };
  18106. /**
  18107. * get a light node using its scene-generated unique ID
  18108. * @param {number} the light's unique id
  18109. * @return {BABYLON.Light|null} the light or null if none found.
  18110. */
  18111. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18112. for (var index = 0; index < this.lights.length; index++) {
  18113. if (this.lights[index].uniqueId === uniqueId) {
  18114. return this.lights[index];
  18115. }
  18116. }
  18117. return null;
  18118. };
  18119. /**
  18120. * get a particle system by id
  18121. * @param id {number} the particle system id
  18122. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  18123. */
  18124. Scene.prototype.getParticleSystemByID = function (id) {
  18125. for (var index = 0; index < this.particleSystems.length; index++) {
  18126. if (this.particleSystems[index].id === id) {
  18127. return this.particleSystems[index];
  18128. }
  18129. }
  18130. return null;
  18131. };
  18132. /**
  18133. * get a geometry using its ID
  18134. * @param {string} the geometry's id
  18135. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18136. */
  18137. Scene.prototype.getGeometryByID = function (id) {
  18138. for (var index = 0; index < this._geometries.length; index++) {
  18139. if (this._geometries[index].id === id) {
  18140. return this._geometries[index];
  18141. }
  18142. }
  18143. return null;
  18144. };
  18145. /**
  18146. * add a new geometry to this scene.
  18147. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18148. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18149. * @return {boolean} was the geometry added or not
  18150. */
  18151. Scene.prototype.pushGeometry = function (geometry, force) {
  18152. if (!force && this.getGeometryByID(geometry.id)) {
  18153. return false;
  18154. }
  18155. this._geometries.push(geometry);
  18156. //notify the collision coordinator
  18157. if (this.collisionCoordinator) {
  18158. this.collisionCoordinator.onGeometryAdded(geometry);
  18159. }
  18160. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18161. return true;
  18162. };
  18163. /**
  18164. * Removes an existing geometry
  18165. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18166. * @return {boolean} was the geometry removed or not
  18167. */
  18168. Scene.prototype.removeGeometry = function (geometry) {
  18169. var index = this._geometries.indexOf(geometry);
  18170. if (index > -1) {
  18171. this._geometries.splice(index, 1);
  18172. //notify the collision coordinator
  18173. if (this.collisionCoordinator) {
  18174. this.collisionCoordinator.onGeometryDeleted(geometry);
  18175. }
  18176. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18177. return true;
  18178. }
  18179. return false;
  18180. };
  18181. Scene.prototype.getGeometries = function () {
  18182. return this._geometries;
  18183. };
  18184. /**
  18185. * Get the first added mesh found of a given ID
  18186. * @param {string} id - the id to search for
  18187. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18188. */
  18189. Scene.prototype.getMeshByID = function (id) {
  18190. for (var index = 0; index < this.meshes.length; index++) {
  18191. if (this.meshes[index].id === id) {
  18192. return this.meshes[index];
  18193. }
  18194. }
  18195. return null;
  18196. };
  18197. Scene.prototype.getMeshesByID = function (id) {
  18198. return this.meshes.filter(function (m) {
  18199. return m.id === id;
  18200. });
  18201. };
  18202. /**
  18203. * Get a mesh with its auto-generated unique id
  18204. * @param {number} uniqueId - the unique id to search for
  18205. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18206. */
  18207. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18208. for (var index = 0; index < this.meshes.length; index++) {
  18209. if (this.meshes[index].uniqueId === uniqueId) {
  18210. return this.meshes[index];
  18211. }
  18212. }
  18213. return null;
  18214. };
  18215. /**
  18216. * Get a the last added mesh found of a given ID
  18217. * @param {string} id - the id to search for
  18218. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18219. */
  18220. Scene.prototype.getLastMeshByID = function (id) {
  18221. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18222. if (this.meshes[index].id === id) {
  18223. return this.meshes[index];
  18224. }
  18225. }
  18226. return null;
  18227. };
  18228. /**
  18229. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18230. * @param {string} id - the id to search for
  18231. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18232. */
  18233. Scene.prototype.getLastEntryByID = function (id) {
  18234. var index;
  18235. for (index = this.meshes.length - 1; index >= 0; index--) {
  18236. if (this.meshes[index].id === id) {
  18237. return this.meshes[index];
  18238. }
  18239. }
  18240. for (index = this.cameras.length - 1; index >= 0; index--) {
  18241. if (this.cameras[index].id === id) {
  18242. return this.cameras[index];
  18243. }
  18244. }
  18245. for (index = this.lights.length - 1; index >= 0; index--) {
  18246. if (this.lights[index].id === id) {
  18247. return this.lights[index];
  18248. }
  18249. }
  18250. return null;
  18251. };
  18252. Scene.prototype.getNodeByID = function (id) {
  18253. var mesh = this.getMeshByID(id);
  18254. if (mesh) {
  18255. return mesh;
  18256. }
  18257. var light = this.getLightByID(id);
  18258. if (light) {
  18259. return light;
  18260. }
  18261. var camera = this.getCameraByID(id);
  18262. if (camera) {
  18263. return camera;
  18264. }
  18265. var bone = this.getBoneByID(id);
  18266. return bone;
  18267. };
  18268. Scene.prototype.getNodeByName = function (name) {
  18269. var mesh = this.getMeshByName(name);
  18270. if (mesh) {
  18271. return mesh;
  18272. }
  18273. var light = this.getLightByName(name);
  18274. if (light) {
  18275. return light;
  18276. }
  18277. var camera = this.getCameraByName(name);
  18278. if (camera) {
  18279. return camera;
  18280. }
  18281. var bone = this.getBoneByName(name);
  18282. return bone;
  18283. };
  18284. Scene.prototype.getMeshByName = function (name) {
  18285. for (var index = 0; index < this.meshes.length; index++) {
  18286. if (this.meshes[index].name === name) {
  18287. return this.meshes[index];
  18288. }
  18289. }
  18290. return null;
  18291. };
  18292. Scene.prototype.getSoundByName = function (name) {
  18293. var index;
  18294. if (BABYLON.AudioEngine) {
  18295. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18296. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18297. return this.mainSoundTrack.soundCollection[index];
  18298. }
  18299. }
  18300. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18301. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18302. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18303. return this.soundTracks[sdIndex].soundCollection[index];
  18304. }
  18305. }
  18306. }
  18307. }
  18308. return null;
  18309. };
  18310. Scene.prototype.getLastSkeletonByID = function (id) {
  18311. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18312. if (this.skeletons[index].id === id) {
  18313. return this.skeletons[index];
  18314. }
  18315. }
  18316. return null;
  18317. };
  18318. Scene.prototype.getSkeletonById = function (id) {
  18319. for (var index = 0; index < this.skeletons.length; index++) {
  18320. if (this.skeletons[index].id === id) {
  18321. return this.skeletons[index];
  18322. }
  18323. }
  18324. return null;
  18325. };
  18326. Scene.prototype.getSkeletonByName = function (name) {
  18327. for (var index = 0; index < this.skeletons.length; index++) {
  18328. if (this.skeletons[index].name === name) {
  18329. return this.skeletons[index];
  18330. }
  18331. }
  18332. return null;
  18333. };
  18334. Scene.prototype.getMorphTargetManagerById = function (id) {
  18335. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18336. if (this.morphTargetManagers[index].uniqueId === id) {
  18337. return this.morphTargetManagers[index];
  18338. }
  18339. }
  18340. return null;
  18341. };
  18342. Scene.prototype.isActiveMesh = function (mesh) {
  18343. return (this._activeMeshes.indexOf(mesh) !== -1);
  18344. };
  18345. /**
  18346. * Return a the first highlight layer of the scene with a given name.
  18347. * @param name The name of the highlight layer to look for.
  18348. * @return The highlight layer if found otherwise null.
  18349. */
  18350. Scene.prototype.getHighlightLayerByName = function (name) {
  18351. for (var index = 0; index < this.highlightLayers.length; index++) {
  18352. if (this.highlightLayers[index].name === name) {
  18353. return this.highlightLayers[index];
  18354. }
  18355. }
  18356. return null;
  18357. };
  18358. Object.defineProperty(Scene.prototype, "uid", {
  18359. /**
  18360. * Return a unique id as a string which can serve as an identifier for the scene
  18361. */
  18362. get: function () {
  18363. if (!this._uid) {
  18364. this._uid = BABYLON.Tools.RandomId();
  18365. }
  18366. return this._uid;
  18367. },
  18368. enumerable: true,
  18369. configurable: true
  18370. });
  18371. /**
  18372. * Add an externaly attached data from its key.
  18373. * This method call will fail and return false, if such key already exists.
  18374. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18375. * @param key the unique key that identifies the data
  18376. * @param data the data object to associate to the key for this Engine instance
  18377. * @return true if no such key were already present and the data was added successfully, false otherwise
  18378. */
  18379. Scene.prototype.addExternalData = function (key, data) {
  18380. if (!this._externalData) {
  18381. this._externalData = new BABYLON.StringDictionary();
  18382. }
  18383. return this._externalData.add(key, data);
  18384. };
  18385. /**
  18386. * Get an externaly attached data from its key
  18387. * @param key the unique key that identifies the data
  18388. * @return the associated data, if present (can be null), or undefined if not present
  18389. */
  18390. Scene.prototype.getExternalData = function (key) {
  18391. if (!this._externalData) {
  18392. return null;
  18393. }
  18394. return this._externalData.get(key);
  18395. };
  18396. /**
  18397. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18398. * @param key the unique key that identifies the data
  18399. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18400. * @return the associated data, can be null if the factory returned null.
  18401. */
  18402. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18403. if (!this._externalData) {
  18404. this._externalData = new BABYLON.StringDictionary();
  18405. }
  18406. return this._externalData.getOrAddWithFactory(key, factory);
  18407. };
  18408. /**
  18409. * Remove an externaly attached data from the Engine instance
  18410. * @param key the unique key that identifies the data
  18411. * @return true if the data was successfully removed, false if it doesn't exist
  18412. */
  18413. Scene.prototype.removeExternalData = function (key) {
  18414. return this._externalData.remove(key);
  18415. };
  18416. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18417. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18418. var material = subMesh.getMaterial();
  18419. if (mesh.showSubMeshesBoundingBox) {
  18420. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18421. }
  18422. if (material) {
  18423. // Render targets
  18424. if (material.getRenderTargetTextures) {
  18425. if (this._processedMaterials.indexOf(material) === -1) {
  18426. this._processedMaterials.push(material);
  18427. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18428. }
  18429. }
  18430. // Dispatch
  18431. this._activeIndices.addCount(subMesh.indexCount, false);
  18432. this._renderingManager.dispatch(subMesh);
  18433. }
  18434. }
  18435. };
  18436. Scene.prototype._isInIntermediateRendering = function () {
  18437. return this._intermediateRendering;
  18438. };
  18439. Scene.prototype._evaluateActiveMeshes = function () {
  18440. this.activeCamera._activeMeshes.reset();
  18441. this._activeMeshes.reset();
  18442. this._renderingManager.reset();
  18443. this._processedMaterials.reset();
  18444. this._activeParticleSystems.reset();
  18445. this._activeSkeletons.reset();
  18446. this._softwareSkinnedMeshes.reset();
  18447. if (this._boundingBoxRenderer) {
  18448. this._boundingBoxRenderer.reset();
  18449. }
  18450. // Meshes
  18451. var meshes;
  18452. var len;
  18453. if (this._selectionOctree) {
  18454. var selection = this._selectionOctree.select(this._frustumPlanes);
  18455. meshes = selection.data;
  18456. len = selection.length;
  18457. }
  18458. else {
  18459. len = this.meshes.length;
  18460. meshes = this.meshes;
  18461. }
  18462. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18463. var mesh = meshes[meshIndex];
  18464. if (mesh.isBlocked) {
  18465. continue;
  18466. }
  18467. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18468. if (!mesh.isReady() || !mesh.isEnabled()) {
  18469. continue;
  18470. }
  18471. mesh.computeWorldMatrix();
  18472. // Intersections
  18473. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18474. this._meshesForIntersections.pushNoDuplicate(mesh);
  18475. }
  18476. // Switch to current LOD
  18477. var meshLOD = mesh.getLOD(this.activeCamera);
  18478. if (!meshLOD) {
  18479. continue;
  18480. }
  18481. mesh._preActivate();
  18482. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18483. this._activeMeshes.push(mesh);
  18484. this.activeCamera._activeMeshes.push(mesh);
  18485. mesh._activate(this._renderId);
  18486. if (meshLOD !== mesh) {
  18487. meshLOD._activate(this._renderId);
  18488. }
  18489. this._activeMesh(mesh, meshLOD);
  18490. }
  18491. }
  18492. // Particle systems
  18493. this._particlesDuration.beginMonitoring();
  18494. var beforeParticlesDate = BABYLON.Tools.Now;
  18495. if (this.particlesEnabled) {
  18496. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18497. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18498. var particleSystem = this.particleSystems[particleIndex];
  18499. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18500. continue;
  18501. }
  18502. var emitter = particleSystem.emitter;
  18503. if (!emitter.position || emitter.isEnabled()) {
  18504. this._activeParticleSystems.push(particleSystem);
  18505. particleSystem.animate();
  18506. this._renderingManager.dispatchParticles(particleSystem);
  18507. }
  18508. }
  18509. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18510. }
  18511. this._particlesDuration.endMonitoring(false);
  18512. };
  18513. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18514. if (mesh.skeleton && this.skeletonsEnabled) {
  18515. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18516. mesh.skeleton.prepare();
  18517. }
  18518. if (!mesh.computeBonesUsingShaders) {
  18519. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18520. }
  18521. }
  18522. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18523. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18524. }
  18525. if (mesh && mesh.subMeshes) {
  18526. // Submeshes Octrees
  18527. var len;
  18528. var subMeshes;
  18529. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18530. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18531. len = intersections.length;
  18532. subMeshes = intersections.data;
  18533. }
  18534. else {
  18535. subMeshes = mesh.subMeshes;
  18536. len = subMeshes.length;
  18537. }
  18538. for (var subIndex = 0; subIndex < len; subIndex++) {
  18539. var subMesh = subMeshes[subIndex];
  18540. this._evaluateSubMesh(subMesh, mesh);
  18541. }
  18542. }
  18543. };
  18544. Scene.prototype.updateTransformMatrix = function (force) {
  18545. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18546. };
  18547. Scene.prototype._renderForCamera = function (camera) {
  18548. var engine = this._engine;
  18549. var startTime = BABYLON.Tools.Now;
  18550. this.activeCamera = camera;
  18551. if (!this.activeCamera)
  18552. throw new Error("Active camera not set");
  18553. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18554. // Viewport
  18555. engine.setViewport(this.activeCamera.viewport);
  18556. // Camera
  18557. this.resetCachedMaterial();
  18558. this._renderId++;
  18559. this.updateTransformMatrix();
  18560. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18561. // Meshes
  18562. this._evaluateActiveMeshesDuration.beginMonitoring();
  18563. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18564. this._evaluateActiveMeshes();
  18565. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18566. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18567. // Software skinning
  18568. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18569. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18570. mesh.applySkeleton(mesh.skeleton);
  18571. }
  18572. // Render targets
  18573. this._renderTargetsDuration.beginMonitoring();
  18574. var needsRestoreFrameBuffer = false;
  18575. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18576. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18577. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18578. }
  18579. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18580. this._intermediateRendering = true;
  18581. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18582. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18583. var renderTarget = this._renderTargets.data[renderIndex];
  18584. if (renderTarget._shouldRender()) {
  18585. this._renderId++;
  18586. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18587. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18588. }
  18589. }
  18590. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18591. this._intermediateRendering = false;
  18592. this._renderId++;
  18593. needsRestoreFrameBuffer = true; // Restore back buffer
  18594. }
  18595. // Render HighlightLayer Texture
  18596. var stencilState = this._engine.getStencilBuffer();
  18597. var renderhighlights = false;
  18598. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18599. this._intermediateRendering = true;
  18600. for (var i = 0; i < this.highlightLayers.length; i++) {
  18601. var highlightLayer = this.highlightLayers[i];
  18602. if (highlightLayer.shouldRender() &&
  18603. (!highlightLayer.camera ||
  18604. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18605. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18606. renderhighlights = true;
  18607. var renderTarget = highlightLayer._mainTexture;
  18608. if (renderTarget._shouldRender()) {
  18609. this._renderId++;
  18610. renderTarget.render(false, false);
  18611. needsRestoreFrameBuffer = true;
  18612. }
  18613. }
  18614. }
  18615. this._intermediateRendering = false;
  18616. this._renderId++;
  18617. }
  18618. if (needsRestoreFrameBuffer) {
  18619. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18620. }
  18621. this._renderTargetsDuration.endMonitoring(false);
  18622. // Prepare Frame
  18623. this.postProcessManager._prepareFrame();
  18624. this._renderDuration.beginMonitoring();
  18625. // Backgrounds
  18626. var layerIndex;
  18627. var layer;
  18628. if (this.layers.length) {
  18629. engine.setDepthBuffer(false);
  18630. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18631. layer = this.layers[layerIndex];
  18632. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18633. layer.render();
  18634. }
  18635. }
  18636. engine.setDepthBuffer(true);
  18637. }
  18638. // Render
  18639. BABYLON.Tools.StartPerformanceCounter("Main render");
  18640. // Activate HighlightLayer stencil
  18641. if (renderhighlights) {
  18642. this._engine.setStencilBuffer(true);
  18643. }
  18644. this._renderingManager.render(null, null, true, true);
  18645. // Restore HighlightLayer stencil
  18646. if (renderhighlights) {
  18647. this._engine.setStencilBuffer(stencilState);
  18648. }
  18649. BABYLON.Tools.EndPerformanceCounter("Main render");
  18650. // Bounding boxes
  18651. if (this._boundingBoxRenderer) {
  18652. this._boundingBoxRenderer.render();
  18653. }
  18654. // Lens flares
  18655. if (this.lensFlaresEnabled) {
  18656. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18657. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18658. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18659. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18660. lensFlareSystem.render();
  18661. }
  18662. }
  18663. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18664. }
  18665. // Foregrounds
  18666. if (this.layers.length) {
  18667. engine.setDepthBuffer(false);
  18668. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18669. layer = this.layers[layerIndex];
  18670. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18671. layer.render();
  18672. }
  18673. }
  18674. engine.setDepthBuffer(true);
  18675. }
  18676. // Highlight Layer
  18677. if (renderhighlights) {
  18678. engine.setDepthBuffer(false);
  18679. for (var i = 0; i < this.highlightLayers.length; i++) {
  18680. if (this.highlightLayers[i].shouldRender()) {
  18681. this.highlightLayers[i].render();
  18682. }
  18683. }
  18684. engine.setDepthBuffer(true);
  18685. }
  18686. this._renderDuration.endMonitoring(false);
  18687. // Finalize frame
  18688. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18689. // Update camera
  18690. this.activeCamera._updateFromScene();
  18691. // Reset some special arrays
  18692. this._renderTargets.reset();
  18693. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18694. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18695. };
  18696. Scene.prototype._processSubCameras = function (camera) {
  18697. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18698. this._renderForCamera(camera);
  18699. return;
  18700. }
  18701. // rig cameras
  18702. for (var index = 0; index < camera._rigCameras.length; index++) {
  18703. this._renderForCamera(camera._rigCameras[index]);
  18704. }
  18705. this.activeCamera = camera;
  18706. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18707. // Update camera
  18708. this.activeCamera._updateFromScene();
  18709. };
  18710. Scene.prototype._checkIntersections = function () {
  18711. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18712. var sourceMesh = this._meshesForIntersections.data[index];
  18713. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18714. var action = sourceMesh.actionManager.actions[actionIndex];
  18715. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18716. var parameters = action.getTriggerParameter();
  18717. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18718. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18719. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18720. if (areIntersecting && currentIntersectionInProgress === -1) {
  18721. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18722. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18723. sourceMesh._intersectionsInProgress.push(otherMesh);
  18724. }
  18725. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18726. sourceMesh._intersectionsInProgress.push(otherMesh);
  18727. }
  18728. }
  18729. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18730. //They intersected, and now they don't.
  18731. //is this trigger an exit trigger? execute an event.
  18732. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18733. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18734. }
  18735. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18736. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18737. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18738. }
  18739. }
  18740. }
  18741. }
  18742. }
  18743. };
  18744. Scene.prototype.render = function () {
  18745. if (this.isDisposed) {
  18746. return;
  18747. }
  18748. this._lastFrameDuration.beginMonitoring();
  18749. this._particlesDuration.fetchNewFrame();
  18750. this._spritesDuration.fetchNewFrame();
  18751. this._activeParticles.fetchNewFrame();
  18752. this._renderDuration.fetchNewFrame();
  18753. this._renderTargetsDuration.fetchNewFrame();
  18754. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18755. this._totalVertices.fetchNewFrame();
  18756. this._activeIndices.fetchNewFrame();
  18757. this._activeBones.fetchNewFrame();
  18758. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18759. this._meshesForIntersections.reset();
  18760. this.resetCachedMaterial();
  18761. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18762. // Actions
  18763. if (this.actionManager) {
  18764. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18765. }
  18766. //Simplification Queue
  18767. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18768. this.simplificationQueue.executeNext();
  18769. }
  18770. if (this._engine.isDeterministicLockStep()) {
  18771. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18772. var defaultTimeStep = (60.0 / 1000.0);
  18773. if (this._physicsEngine) {
  18774. defaultTimeStep = this._physicsEngine.getTimeStep();
  18775. }
  18776. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18777. this._timeAccumulator += deltaTime;
  18778. // compute the amount of fixed steps we should have taken since the last step
  18779. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  18780. internalSteps = Math.min(internalSteps, maxSubSteps);
  18781. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  18782. this.onBeforeStepObservable.notifyObservers(this);
  18783. // Animations
  18784. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  18785. this._animate();
  18786. // Physics
  18787. if (this._physicsEngine) {
  18788. BABYLON.Tools.StartPerformanceCounter("Physics");
  18789. this._physicsEngine._step(defaultTimeStep);
  18790. BABYLON.Tools.EndPerformanceCounter("Physics");
  18791. }
  18792. this._timeAccumulator -= defaultTimeStep;
  18793. this.onAfterStepObservable.notifyObservers(this);
  18794. this._currentStepId++;
  18795. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  18796. // Q: can this be optimized by putting some code in the afterStep callback?
  18797. // I had to put this code here, otherwise mesh attached to bones of another mesh skeleton,
  18798. // would return incorrect positions for internal stepIds (non-rendered steps)
  18799. this._evaluateActiveMeshes();
  18800. }
  18801. }
  18802. }
  18803. else {
  18804. // Animations
  18805. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18806. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18807. this._animate();
  18808. // Physics
  18809. if (this._physicsEngine) {
  18810. BABYLON.Tools.StartPerformanceCounter("Physics");
  18811. this._physicsEngine._step(deltaTime / 1000.0);
  18812. BABYLON.Tools.EndPerformanceCounter("Physics");
  18813. }
  18814. }
  18815. // Before render
  18816. this.onBeforeRenderObservable.notifyObservers(this);
  18817. // Customs render targets
  18818. this._renderTargetsDuration.beginMonitoring();
  18819. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18820. var engine = this.getEngine();
  18821. var currentActiveCamera = this.activeCamera;
  18822. if (this.renderTargetsEnabled) {
  18823. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18824. this._intermediateRendering = true;
  18825. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18826. var renderTarget = this.customRenderTargets[customIndex];
  18827. if (renderTarget._shouldRender()) {
  18828. this._renderId++;
  18829. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18830. if (!this.activeCamera)
  18831. throw new Error("Active camera not set");
  18832. // Viewport
  18833. engine.setViewport(this.activeCamera.viewport);
  18834. // Camera
  18835. this.updateTransformMatrix();
  18836. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18837. }
  18838. }
  18839. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18840. this._intermediateRendering = false;
  18841. this._renderId++;
  18842. }
  18843. // Restore back buffer
  18844. if (this.customRenderTargets.length > 0) {
  18845. engine.restoreDefaultFramebuffer();
  18846. }
  18847. this._renderTargetsDuration.endMonitoring();
  18848. this.activeCamera = currentActiveCamera;
  18849. // Procedural textures
  18850. if (this.proceduralTexturesEnabled) {
  18851. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18852. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18853. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18854. if (proceduralTexture._shouldRender()) {
  18855. proceduralTexture.render();
  18856. }
  18857. }
  18858. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18859. }
  18860. // Clear
  18861. if (this.autoClearDepthAndStencil || this.autoClear) {
  18862. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  18863. }
  18864. // Shadows
  18865. if (this.shadowsEnabled) {
  18866. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18867. var light = this.lights[lightIndex];
  18868. var shadowGenerator = light.getShadowGenerator();
  18869. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  18870. var shadowMap = shadowGenerator.getShadowMap();
  18871. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  18872. this._renderTargets.push(shadowMap);
  18873. }
  18874. }
  18875. }
  18876. }
  18877. // Depth renderer
  18878. if (this._depthRenderer) {
  18879. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18880. }
  18881. // Geometry renderer
  18882. if (this._geometryBufferRenderer) {
  18883. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  18884. }
  18885. // RenderPipeline
  18886. if (this._postProcessRenderPipelineManager) {
  18887. this._postProcessRenderPipelineManager.update();
  18888. }
  18889. // Multi-cameras?
  18890. if (this.activeCameras.length > 0) {
  18891. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18892. if (cameraIndex > 0) {
  18893. this._engine.clear(null, false, true, true);
  18894. }
  18895. this._processSubCameras(this.activeCameras[cameraIndex]);
  18896. }
  18897. }
  18898. else {
  18899. if (!this.activeCamera) {
  18900. throw new Error("No camera defined");
  18901. }
  18902. this._processSubCameras(this.activeCamera);
  18903. }
  18904. // Intersection checks
  18905. this._checkIntersections();
  18906. // Update the audio listener attached to the camera
  18907. if (BABYLON.AudioEngine) {
  18908. this._updateAudioParameters();
  18909. }
  18910. // After render
  18911. if (this.afterRender) {
  18912. this.afterRender();
  18913. }
  18914. this.onAfterRenderObservable.notifyObservers(this);
  18915. // Cleaning
  18916. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18917. this._toBeDisposed.data[index].dispose();
  18918. this._toBeDisposed[index] = null;
  18919. }
  18920. this._toBeDisposed.reset();
  18921. if (this.dumpNextRenderTargets) {
  18922. this.dumpNextRenderTargets = false;
  18923. }
  18924. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18925. this._lastFrameDuration.endMonitoring();
  18926. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18927. this._totalLightsCounter.addCount(this.lights.length, true);
  18928. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18929. this._totalTexturesCounter.addCount(this.textures.length, true);
  18930. this._activeBones.addCount(0, true);
  18931. this._activeIndices.addCount(0, true);
  18932. this._activeParticles.addCount(0, true);
  18933. };
  18934. Scene.prototype._updateAudioParameters = function () {
  18935. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18936. return;
  18937. }
  18938. var listeningCamera;
  18939. var audioEngine = BABYLON.Engine.audioEngine;
  18940. if (this.activeCameras.length > 0) {
  18941. listeningCamera = this.activeCameras[0];
  18942. }
  18943. else {
  18944. listeningCamera = this.activeCamera;
  18945. }
  18946. if (listeningCamera && audioEngine.canUseWebAudio) {
  18947. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18948. // for VR cameras
  18949. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  18950. listeningCamera = listeningCamera.rigCameras[0];
  18951. }
  18952. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18953. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18954. cameraDirection.normalize();
  18955. // To avoid some errors on GearVR
  18956. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  18957. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18958. }
  18959. var i;
  18960. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18961. var sound = this.mainSoundTrack.soundCollection[i];
  18962. if (sound.useCustomAttenuation) {
  18963. sound.updateDistanceFromListener();
  18964. }
  18965. }
  18966. for (i = 0; i < this.soundTracks.length; i++) {
  18967. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18968. sound = this.soundTracks[i].soundCollection[j];
  18969. if (sound.useCustomAttenuation) {
  18970. sound.updateDistanceFromListener();
  18971. }
  18972. }
  18973. }
  18974. }
  18975. };
  18976. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18977. // Audio
  18978. get: function () {
  18979. return this._audioEnabled;
  18980. },
  18981. set: function (value) {
  18982. this._audioEnabled = value;
  18983. if (BABYLON.AudioEngine) {
  18984. if (this._audioEnabled) {
  18985. this._enableAudio();
  18986. }
  18987. else {
  18988. this._disableAudio();
  18989. }
  18990. }
  18991. },
  18992. enumerable: true,
  18993. configurable: true
  18994. });
  18995. Scene.prototype._disableAudio = function () {
  18996. var i;
  18997. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18998. this.mainSoundTrack.soundCollection[i].pause();
  18999. }
  19000. for (i = 0; i < this.soundTracks.length; i++) {
  19001. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19002. this.soundTracks[i].soundCollection[j].pause();
  19003. }
  19004. }
  19005. };
  19006. Scene.prototype._enableAudio = function () {
  19007. var i;
  19008. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19009. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19010. this.mainSoundTrack.soundCollection[i].play();
  19011. }
  19012. }
  19013. for (i = 0; i < this.soundTracks.length; i++) {
  19014. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19015. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19016. this.soundTracks[i].soundCollection[j].play();
  19017. }
  19018. }
  19019. }
  19020. };
  19021. Object.defineProperty(Scene.prototype, "headphone", {
  19022. get: function () {
  19023. return this._headphone;
  19024. },
  19025. set: function (value) {
  19026. this._headphone = value;
  19027. if (BABYLON.AudioEngine) {
  19028. if (this._headphone) {
  19029. this._switchAudioModeForHeadphones();
  19030. }
  19031. else {
  19032. this._switchAudioModeForNormalSpeakers();
  19033. }
  19034. }
  19035. },
  19036. enumerable: true,
  19037. configurable: true
  19038. });
  19039. Scene.prototype._switchAudioModeForHeadphones = function () {
  19040. this.mainSoundTrack.switchPanningModelToHRTF();
  19041. for (var i = 0; i < this.soundTracks.length; i++) {
  19042. this.soundTracks[i].switchPanningModelToHRTF();
  19043. }
  19044. };
  19045. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19046. this.mainSoundTrack.switchPanningModelToEqualPower();
  19047. for (var i = 0; i < this.soundTracks.length; i++) {
  19048. this.soundTracks[i].switchPanningModelToEqualPower();
  19049. }
  19050. };
  19051. Scene.prototype.enableDepthRenderer = function () {
  19052. if (this._depthRenderer) {
  19053. return this._depthRenderer;
  19054. }
  19055. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19056. return this._depthRenderer;
  19057. };
  19058. Scene.prototype.disableDepthRenderer = function () {
  19059. if (!this._depthRenderer) {
  19060. return;
  19061. }
  19062. this._depthRenderer.dispose();
  19063. this._depthRenderer = null;
  19064. };
  19065. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  19066. if (ratio === void 0) { ratio = 1; }
  19067. if (this._geometryBufferRenderer) {
  19068. return this._geometryBufferRenderer;
  19069. }
  19070. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  19071. if (!this._geometryBufferRenderer.isSupported) {
  19072. this._geometryBufferRenderer = null;
  19073. }
  19074. return this._geometryBufferRenderer;
  19075. };
  19076. Scene.prototype.disableGeometryBufferRenderer = function () {
  19077. if (!this._geometryBufferRenderer) {
  19078. return;
  19079. }
  19080. this._geometryBufferRenderer.dispose();
  19081. this._geometryBufferRenderer = null;
  19082. };
  19083. Scene.prototype.freezeMaterials = function () {
  19084. for (var i = 0; i < this.materials.length; i++) {
  19085. this.materials[i].freeze();
  19086. }
  19087. };
  19088. Scene.prototype.unfreezeMaterials = function () {
  19089. for (var i = 0; i < this.materials.length; i++) {
  19090. this.materials[i].unfreeze();
  19091. }
  19092. };
  19093. Scene.prototype.dispose = function () {
  19094. this.beforeRender = null;
  19095. this.afterRender = null;
  19096. this.skeletons = [];
  19097. this.morphTargetManagers = [];
  19098. this.importedMeshesFiles = new Array();
  19099. this.resetCachedMaterial();
  19100. if (this._depthRenderer) {
  19101. this._depthRenderer.dispose();
  19102. }
  19103. if (this._gamepadManager) {
  19104. this._gamepadManager.dispose();
  19105. this._gamepadManager = null;
  19106. }
  19107. // Smart arrays
  19108. if (this.activeCamera) {
  19109. this.activeCamera._activeMeshes.dispose();
  19110. this.activeCamera = null;
  19111. }
  19112. this._activeMeshes.dispose();
  19113. this._renderingManager.dispose();
  19114. this._processedMaterials.dispose();
  19115. this._activeParticleSystems.dispose();
  19116. this._activeSkeletons.dispose();
  19117. this._softwareSkinnedMeshes.dispose();
  19118. this._renderTargets.dispose();
  19119. if (this._boundingBoxRenderer) {
  19120. this._boundingBoxRenderer.dispose();
  19121. }
  19122. this._meshesForIntersections.dispose();
  19123. this._toBeDisposed.dispose();
  19124. // Debug layer
  19125. if (this._debugLayer) {
  19126. this._debugLayer.hide();
  19127. }
  19128. // Events
  19129. this.onDisposeObservable.notifyObservers(this);
  19130. this.onDisposeObservable.clear();
  19131. this.onBeforeRenderObservable.clear();
  19132. this.onAfterRenderObservable.clear();
  19133. this.detachControl();
  19134. // Release sounds & sounds tracks
  19135. if (BABYLON.AudioEngine) {
  19136. this.disposeSounds();
  19137. }
  19138. // VR Helper
  19139. if (this.VRHelper) {
  19140. this.VRHelper.dispose();
  19141. }
  19142. // Detach cameras
  19143. var canvas = this._engine.getRenderingCanvas();
  19144. var index;
  19145. for (index = 0; index < this.cameras.length; index++) {
  19146. this.cameras[index].detachControl(canvas);
  19147. }
  19148. // Release lights
  19149. while (this.lights.length) {
  19150. this.lights[0].dispose();
  19151. }
  19152. // Release meshes
  19153. while (this.meshes.length) {
  19154. this.meshes[0].dispose(true);
  19155. }
  19156. // Release cameras
  19157. while (this.cameras.length) {
  19158. this.cameras[0].dispose();
  19159. }
  19160. // Release materials
  19161. if (this.defaultMaterial) {
  19162. this.defaultMaterial.dispose();
  19163. }
  19164. while (this.multiMaterials.length) {
  19165. this.multiMaterials[0].dispose();
  19166. }
  19167. while (this.materials.length) {
  19168. this.materials[0].dispose();
  19169. }
  19170. // Release particles
  19171. while (this.particleSystems.length) {
  19172. this.particleSystems[0].dispose();
  19173. }
  19174. // Release sprites
  19175. while (this.spriteManagers.length) {
  19176. this.spriteManagers[0].dispose();
  19177. }
  19178. // Release postProcesses
  19179. while (this.postProcesses.length) {
  19180. this.postProcesses[0].dispose();
  19181. }
  19182. // Release layers
  19183. while (this.layers.length) {
  19184. this.layers[0].dispose();
  19185. }
  19186. while (this.highlightLayers.length) {
  19187. this.highlightLayers[0].dispose();
  19188. }
  19189. // Release textures
  19190. while (this.textures.length) {
  19191. this.textures[0].dispose();
  19192. }
  19193. // Release UBO
  19194. this._sceneUbo.dispose();
  19195. // Post-processes
  19196. this.postProcessManager.dispose();
  19197. if (this._postProcessRenderPipelineManager) {
  19198. this._postProcessRenderPipelineManager.dispose();
  19199. }
  19200. // Physics
  19201. if (this._physicsEngine) {
  19202. this.disablePhysicsEngine();
  19203. }
  19204. // Remove from engine
  19205. index = this._engine.scenes.indexOf(this);
  19206. if (index > -1) {
  19207. this._engine.scenes.splice(index, 1);
  19208. }
  19209. this._engine.wipeCaches();
  19210. this._engine = null;
  19211. this.defaultMaterial = null;
  19212. this.multiMaterials = null;
  19213. this.materials = null;
  19214. };
  19215. Object.defineProperty(Scene.prototype, "isDisposed", {
  19216. get: function () {
  19217. return !this._engine;
  19218. },
  19219. enumerable: true,
  19220. configurable: true
  19221. });
  19222. // Release sounds & sounds tracks
  19223. Scene.prototype.disposeSounds = function () {
  19224. this.mainSoundTrack.dispose();
  19225. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19226. this.soundTracks[scIndex].dispose();
  19227. }
  19228. };
  19229. // Octrees
  19230. Scene.prototype.getWorldExtends = function () {
  19231. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19232. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19233. for (var index = 0; index < this.meshes.length; index++) {
  19234. var mesh = this.meshes[index];
  19235. mesh.computeWorldMatrix(true);
  19236. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19237. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19238. BABYLON.Tools.CheckExtends(minBox, min, max);
  19239. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19240. }
  19241. return {
  19242. min: min,
  19243. max: max
  19244. };
  19245. };
  19246. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19247. if (maxCapacity === void 0) { maxCapacity = 64; }
  19248. if (maxDepth === void 0) { maxDepth = 2; }
  19249. if (!this._selectionOctree) {
  19250. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19251. }
  19252. var worldExtends = this.getWorldExtends();
  19253. // Update octree
  19254. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19255. return this._selectionOctree;
  19256. };
  19257. // Picking
  19258. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19259. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19260. var engine = this._engine;
  19261. if (!camera) {
  19262. if (!this.activeCamera)
  19263. throw new Error("Active camera not set");
  19264. camera = this.activeCamera;
  19265. }
  19266. var cameraViewport = camera.viewport;
  19267. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19268. // Moving coordinates to local viewport world
  19269. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19270. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19271. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19272. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19273. };
  19274. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19275. if (!BABYLON.PickingInfo) {
  19276. return null;
  19277. }
  19278. var engine = this._engine;
  19279. if (!camera) {
  19280. if (!this.activeCamera)
  19281. throw new Error("Active camera not set");
  19282. camera = this.activeCamera;
  19283. }
  19284. var cameraViewport = camera.viewport;
  19285. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19286. var identity = BABYLON.Matrix.Identity();
  19287. // Moving coordinates to local viewport world
  19288. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19289. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19290. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19291. };
  19292. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19293. if (!BABYLON.PickingInfo) {
  19294. return null;
  19295. }
  19296. var pickingInfo = null;
  19297. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19298. var mesh = this.meshes[meshIndex];
  19299. if (predicate) {
  19300. if (!predicate(mesh)) {
  19301. continue;
  19302. }
  19303. }
  19304. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19305. continue;
  19306. }
  19307. var world = mesh.getWorldMatrix();
  19308. var ray = rayFunction(world);
  19309. var result = mesh.intersects(ray, fastCheck);
  19310. if (!result || !result.hit)
  19311. continue;
  19312. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19313. continue;
  19314. pickingInfo = result;
  19315. if (fastCheck) {
  19316. break;
  19317. }
  19318. }
  19319. return pickingInfo || new BABYLON.PickingInfo();
  19320. };
  19321. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19322. if (!BABYLON.PickingInfo) {
  19323. return null;
  19324. }
  19325. var pickingInfos = new Array();
  19326. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19327. var mesh = this.meshes[meshIndex];
  19328. if (predicate) {
  19329. if (!predicate(mesh)) {
  19330. continue;
  19331. }
  19332. }
  19333. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19334. continue;
  19335. }
  19336. var world = mesh.getWorldMatrix();
  19337. var ray = rayFunction(world);
  19338. var result = mesh.intersects(ray, false);
  19339. if (!result || !result.hit)
  19340. continue;
  19341. pickingInfos.push(result);
  19342. }
  19343. return pickingInfos;
  19344. };
  19345. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19346. if (!BABYLON.PickingInfo) {
  19347. return null;
  19348. }
  19349. var pickingInfo = null;
  19350. camera = camera || this.activeCamera;
  19351. if (this.spriteManagers.length > 0) {
  19352. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19353. var spriteManager = this.spriteManagers[spriteIndex];
  19354. if (!spriteManager.isPickable) {
  19355. continue;
  19356. }
  19357. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19358. if (!result || !result.hit)
  19359. continue;
  19360. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19361. continue;
  19362. pickingInfo = result;
  19363. if (fastCheck) {
  19364. break;
  19365. }
  19366. }
  19367. }
  19368. return pickingInfo || new BABYLON.PickingInfo();
  19369. };
  19370. /** Launch a ray to try to pick a mesh in the scene
  19371. * @param x position on screen
  19372. * @param y position on screen
  19373. * @param 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
  19374. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19375. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19376. */
  19377. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19378. var _this = this;
  19379. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19380. };
  19381. /** Launch a ray to try to pick a sprite in the scene
  19382. * @param x position on screen
  19383. * @param y position on screen
  19384. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  19385. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19386. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19387. */
  19388. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19389. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19390. };
  19391. /** Use the given ray to pick a mesh in the scene
  19392. * @param ray The ray to use to pick meshes
  19393. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  19394. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19395. */
  19396. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19397. var _this = this;
  19398. return this._internalPick(function (world) {
  19399. if (!_this._pickWithRayInverseMatrix) {
  19400. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19401. }
  19402. world.invertToRef(_this._pickWithRayInverseMatrix);
  19403. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19404. }, predicate, fastCheck);
  19405. };
  19406. /**
  19407. * Launch a ray to try to pick a mesh in the scene
  19408. * @param x X position on screen
  19409. * @param y Y position on screen
  19410. * @param 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
  19411. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19412. */
  19413. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19414. var _this = this;
  19415. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19416. };
  19417. /**
  19418. * Launch a ray to try to pick a mesh in the scene
  19419. * @param ray Ray to use
  19420. * @param 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
  19421. */
  19422. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19423. var _this = this;
  19424. return this._internalMultiPick(function (world) {
  19425. if (!_this._pickWithRayInverseMatrix) {
  19426. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19427. }
  19428. world.invertToRef(_this._pickWithRayInverseMatrix);
  19429. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19430. }, predicate);
  19431. };
  19432. Scene.prototype.setPointerOverMesh = function (mesh) {
  19433. if (this._pointerOverMesh === mesh) {
  19434. return;
  19435. }
  19436. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19437. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19438. }
  19439. this._pointerOverMesh = mesh;
  19440. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19441. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19442. }
  19443. };
  19444. Scene.prototype.getPointerOverMesh = function () {
  19445. return this._pointerOverMesh;
  19446. };
  19447. Scene.prototype.setPointerOverSprite = function (sprite) {
  19448. if (this._pointerOverSprite === sprite) {
  19449. return;
  19450. }
  19451. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19452. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19453. }
  19454. this._pointerOverSprite = sprite;
  19455. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19456. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19457. }
  19458. };
  19459. Scene.prototype.getPointerOverSprite = function () {
  19460. return this._pointerOverSprite;
  19461. };
  19462. // Physics
  19463. Scene.prototype.getPhysicsEngine = function () {
  19464. return this._physicsEngine;
  19465. };
  19466. /**
  19467. * Enables physics to the current scene
  19468. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19469. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19470. * @return {boolean} was the physics engine initialized
  19471. */
  19472. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19473. if (this._physicsEngine) {
  19474. return true;
  19475. }
  19476. try {
  19477. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19478. return true;
  19479. }
  19480. catch (e) {
  19481. BABYLON.Tools.Error(e.message);
  19482. return false;
  19483. }
  19484. };
  19485. Scene.prototype.disablePhysicsEngine = function () {
  19486. if (!this._physicsEngine) {
  19487. return;
  19488. }
  19489. this._physicsEngine.dispose();
  19490. this._physicsEngine = undefined;
  19491. };
  19492. Scene.prototype.isPhysicsEnabled = function () {
  19493. return this._physicsEngine !== undefined;
  19494. };
  19495. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19496. var mesh = compound.parts[0].mesh;
  19497. mesh.physicsImpostor.dispose();
  19498. mesh.physicsImpostor = null;
  19499. };
  19500. // Misc.
  19501. Scene.prototype._rebuildGeometries = function () {
  19502. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19503. var geometry = _a[_i];
  19504. geometry._rebuild();
  19505. }
  19506. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19507. var mesh = _c[_b];
  19508. mesh._rebuild();
  19509. }
  19510. if (this.postProcessManager) {
  19511. this.postProcessManager._rebuild();
  19512. }
  19513. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19514. var layer = _e[_d];
  19515. layer._rebuild();
  19516. }
  19517. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19518. var highlightLayer = _g[_f];
  19519. highlightLayer._rebuild();
  19520. }
  19521. if (this._boundingBoxRenderer) {
  19522. this._boundingBoxRenderer._rebuild();
  19523. }
  19524. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  19525. var system = _j[_h];
  19526. system.rebuild();
  19527. }
  19528. if (this._postProcessRenderPipelineManager) {
  19529. this._postProcessRenderPipelineManager._rebuild();
  19530. }
  19531. };
  19532. Scene.prototype._rebuildTextures = function () {
  19533. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19534. var texture = _a[_i];
  19535. texture._rebuild();
  19536. }
  19537. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19538. };
  19539. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19540. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19541. if (replace === void 0) { replace = false; }
  19542. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19543. // Dispose existing camera or light in replace mode.
  19544. if (replace) {
  19545. if (this.activeCamera) {
  19546. this.activeCamera.dispose();
  19547. this.activeCamera = null;
  19548. }
  19549. if (this.lights) {
  19550. for (var i = 0; i < this.lights.length; i++) {
  19551. this.lights[i].dispose();
  19552. }
  19553. }
  19554. }
  19555. // Light
  19556. if (this.lights.length === 0) {
  19557. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19558. }
  19559. // Camera
  19560. if (!this.activeCamera) {
  19561. var worldExtends = this.getWorldExtends();
  19562. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19563. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19564. var camera;
  19565. var radius = worldSize.length() * 1.5;
  19566. if (createArcRotateCamera) {
  19567. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19568. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19569. arcRotateCamera.wheelPrecision = 100 / radius;
  19570. camera = arcRotateCamera;
  19571. }
  19572. else {
  19573. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19574. freeCamera.setTarget(worldCenter);
  19575. camera = freeCamera;
  19576. }
  19577. camera.minZ = radius * 0.01;
  19578. camera.maxZ = radius * 100;
  19579. camera.speed = radius * 0.2;
  19580. this.activeCamera = camera;
  19581. if (attachCameraControls) {
  19582. camera.attachControl(this.getEngine().getRenderingCanvas());
  19583. }
  19584. }
  19585. };
  19586. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19587. if (pbr === void 0) { pbr = false; }
  19588. if (scale === void 0) { scale = 1000; }
  19589. if (blur === void 0) { blur = 0; }
  19590. if (environmentTexture) {
  19591. this.environmentTexture = environmentTexture;
  19592. }
  19593. if (!this.environmentTexture) {
  19594. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19595. return;
  19596. }
  19597. // Skybox
  19598. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19599. if (pbr) {
  19600. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19601. hdrSkyboxMaterial.backFaceCulling = false;
  19602. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19603. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19604. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19605. hdrSkyboxMaterial.disableLighting = true;
  19606. hdrSkyboxMaterial.twoSidedLighting = true;
  19607. hdrSkybox.infiniteDistance = true;
  19608. hdrSkybox.material = hdrSkyboxMaterial;
  19609. }
  19610. else {
  19611. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19612. skyboxMaterial.backFaceCulling = false;
  19613. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19614. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19615. skyboxMaterial.disableLighting = true;
  19616. hdrSkybox.infiniteDistance = true;
  19617. hdrSkybox.material = skyboxMaterial;
  19618. }
  19619. return hdrSkybox;
  19620. };
  19621. Scene.prototype.createDefaultVRExperience = function () {
  19622. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19623. };
  19624. // Tags
  19625. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19626. if (tagsQuery === undefined) {
  19627. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19628. return list;
  19629. }
  19630. var listByTags = [];
  19631. forEach = forEach || (function (item) { return; });
  19632. for (var i in list) {
  19633. var item = list[i];
  19634. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19635. listByTags.push(item);
  19636. forEach(item);
  19637. }
  19638. }
  19639. return listByTags;
  19640. };
  19641. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19642. return this._getByTags(this.meshes, tagsQuery, forEach);
  19643. };
  19644. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19645. return this._getByTags(this.cameras, tagsQuery, forEach);
  19646. };
  19647. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19648. return this._getByTags(this.lights, tagsQuery, forEach);
  19649. };
  19650. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19651. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19652. };
  19653. /**
  19654. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19655. * This allowed control for front to back rendering or reversly depending of the special needs.
  19656. *
  19657. * @param renderingGroupId The rendering group id corresponding to its index
  19658. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19659. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19660. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19661. */
  19662. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19663. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19664. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19665. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19666. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19667. };
  19668. /**
  19669. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19670. *
  19671. * @param renderingGroupId The rendering group id corresponding to its index
  19672. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19673. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19674. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19675. */
  19676. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19677. if (depth === void 0) { depth = true; }
  19678. if (stencil === void 0) { stencil = true; }
  19679. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19680. };
  19681. /**
  19682. * Will flag all materials as dirty to trigger new shader compilation
  19683. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19684. */
  19685. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19686. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19687. var material = _a[_i];
  19688. if (predicate && !predicate(material)) {
  19689. continue;
  19690. }
  19691. material.markAsDirty(flag);
  19692. }
  19693. };
  19694. // Statics
  19695. Scene._FOGMODE_NONE = 0;
  19696. Scene._FOGMODE_EXP = 1;
  19697. Scene._FOGMODE_EXP2 = 2;
  19698. Scene._FOGMODE_LINEAR = 3;
  19699. Scene.MinDeltaTime = 1.0;
  19700. Scene.MaxDeltaTime = 1000.0;
  19701. /** The distance in pixel that you have to move to prevent some events */
  19702. Scene.DragMovementThreshold = 10; // in pixels
  19703. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19704. Scene.LongPressDelay = 500; // in milliseconds
  19705. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19706. Scene.DoubleClickDelay = 300; // in milliseconds
  19707. /** If you need to check double click without raising a single click at first click, enable this flag */
  19708. Scene.ExclusiveDoubleClickMode = false;
  19709. return Scene;
  19710. }());
  19711. BABYLON.Scene = Scene;
  19712. })(BABYLON || (BABYLON = {}));
  19713. //# sourceMappingURL=babylon.scene.js.map
  19714. var BABYLON;
  19715. (function (BABYLON) {
  19716. var Buffer = (function () {
  19717. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19718. if (engine instanceof BABYLON.Mesh) {
  19719. this._engine = engine.getScene().getEngine();
  19720. }
  19721. else {
  19722. this._engine = engine;
  19723. }
  19724. this._updatable = updatable;
  19725. this._data = data;
  19726. this._strideSize = stride;
  19727. if (!postponeInternalCreation) {
  19728. this.create();
  19729. }
  19730. this._instanced = instanced;
  19731. this._instanceDivisor = instanced ? 1 : 0;
  19732. }
  19733. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19734. // a lot of these parameters are ignored as they are overriden by the buffer
  19735. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19736. };
  19737. // Properties
  19738. Buffer.prototype.isUpdatable = function () {
  19739. return this._updatable;
  19740. };
  19741. Buffer.prototype.getData = function () {
  19742. return this._data;
  19743. };
  19744. Buffer.prototype.getBuffer = function () {
  19745. return this._buffer;
  19746. };
  19747. Buffer.prototype.getStrideSize = function () {
  19748. return this._strideSize;
  19749. };
  19750. Buffer.prototype.getIsInstanced = function () {
  19751. return this._instanced;
  19752. };
  19753. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19754. get: function () {
  19755. return this._instanceDivisor;
  19756. },
  19757. set: function (value) {
  19758. this._instanceDivisor = value;
  19759. if (value == 0) {
  19760. this._instanced = false;
  19761. }
  19762. else {
  19763. this._instanced = true;
  19764. }
  19765. },
  19766. enumerable: true,
  19767. configurable: true
  19768. });
  19769. // Methods
  19770. Buffer.prototype.create = function (data) {
  19771. if (!data && this._buffer) {
  19772. return; // nothing to do
  19773. }
  19774. data = data || this._data;
  19775. if (!this._buffer) {
  19776. if (this._updatable) {
  19777. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19778. this._data = data;
  19779. }
  19780. else {
  19781. this._buffer = this._engine.createVertexBuffer(data);
  19782. }
  19783. }
  19784. else if (this._updatable) {
  19785. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19786. this._data = data;
  19787. }
  19788. };
  19789. Buffer.prototype._rebuild = function () {
  19790. this._buffer = null;
  19791. this.create(this._data);
  19792. };
  19793. Buffer.prototype.update = function (data) {
  19794. this.create(data);
  19795. };
  19796. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19797. if (!this._buffer) {
  19798. return;
  19799. }
  19800. if (this._updatable) {
  19801. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19802. this._data = null;
  19803. }
  19804. };
  19805. Buffer.prototype.dispose = function () {
  19806. if (!this._buffer) {
  19807. return;
  19808. }
  19809. if (this._engine._releaseBuffer(this._buffer)) {
  19810. this._buffer = null;
  19811. }
  19812. };
  19813. return Buffer;
  19814. }());
  19815. BABYLON.Buffer = Buffer;
  19816. })(BABYLON || (BABYLON = {}));
  19817. //# sourceMappingURL=babylon.buffer.js.map
  19818. var BABYLON;
  19819. (function (BABYLON) {
  19820. var VertexBuffer = (function () {
  19821. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19822. if (!stride) {
  19823. // Deduce stride from kind
  19824. switch (kind) {
  19825. case VertexBuffer.PositionKind:
  19826. stride = 3;
  19827. break;
  19828. case VertexBuffer.NormalKind:
  19829. stride = 3;
  19830. break;
  19831. case VertexBuffer.UVKind:
  19832. case VertexBuffer.UV2Kind:
  19833. case VertexBuffer.UV3Kind:
  19834. case VertexBuffer.UV4Kind:
  19835. case VertexBuffer.UV5Kind:
  19836. case VertexBuffer.UV6Kind:
  19837. stride = 2;
  19838. break;
  19839. case VertexBuffer.TangentKind:
  19840. case VertexBuffer.ColorKind:
  19841. stride = 4;
  19842. break;
  19843. case VertexBuffer.MatricesIndicesKind:
  19844. case VertexBuffer.MatricesIndicesExtraKind:
  19845. stride = 4;
  19846. break;
  19847. case VertexBuffer.MatricesWeightsKind:
  19848. case VertexBuffer.MatricesWeightsExtraKind:
  19849. stride = 4;
  19850. break;
  19851. }
  19852. }
  19853. if (data instanceof BABYLON.Buffer) {
  19854. if (!stride) {
  19855. stride = data.getStrideSize();
  19856. }
  19857. this._buffer = data;
  19858. this._ownsBuffer = false;
  19859. }
  19860. else {
  19861. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19862. this._ownsBuffer = true;
  19863. }
  19864. this._stride = stride;
  19865. this._offset = offset ? offset : 0;
  19866. this._size = size ? size : stride;
  19867. this._kind = kind;
  19868. }
  19869. VertexBuffer.prototype._rebuild = function () {
  19870. if (!this._buffer) {
  19871. return;
  19872. }
  19873. this._buffer._rebuild();
  19874. };
  19875. /**
  19876. * Returns the kind of the VertexBuffer (string).
  19877. */
  19878. VertexBuffer.prototype.getKind = function () {
  19879. return this._kind;
  19880. };
  19881. // Properties
  19882. /**
  19883. * Boolean : is the VertexBuffer updatable ?
  19884. */
  19885. VertexBuffer.prototype.isUpdatable = function () {
  19886. return this._buffer.isUpdatable();
  19887. };
  19888. /**
  19889. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  19890. */
  19891. VertexBuffer.prototype.getData = function () {
  19892. return this._buffer.getData();
  19893. };
  19894. /**
  19895. * Returns the WebGLBuffer associated to the VertexBuffer.
  19896. */
  19897. VertexBuffer.prototype.getBuffer = function () {
  19898. return this._buffer.getBuffer();
  19899. };
  19900. /**
  19901. * Returns the stride of the VertexBuffer (integer).
  19902. */
  19903. VertexBuffer.prototype.getStrideSize = function () {
  19904. return this._stride;
  19905. };
  19906. /**
  19907. * Returns the offset (integer).
  19908. */
  19909. VertexBuffer.prototype.getOffset = function () {
  19910. return this._offset;
  19911. };
  19912. /**
  19913. * Returns the VertexBuffer total size (integer).
  19914. */
  19915. VertexBuffer.prototype.getSize = function () {
  19916. return this._size;
  19917. };
  19918. /**
  19919. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  19920. */
  19921. VertexBuffer.prototype.getIsInstanced = function () {
  19922. return this._buffer.getIsInstanced();
  19923. };
  19924. /**
  19925. * Returns the instancing divisor, zero for non-instanced (integer).
  19926. */
  19927. VertexBuffer.prototype.getInstanceDivisor = function () {
  19928. return this._buffer.instanceDivisor;
  19929. };
  19930. // Methods
  19931. /**
  19932. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  19933. * Returns the created WebGLBuffer.
  19934. */
  19935. VertexBuffer.prototype.create = function (data) {
  19936. return this._buffer.create(data);
  19937. };
  19938. /**
  19939. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19940. * Returns the updated WebGLBuffer.
  19941. */
  19942. VertexBuffer.prototype.update = function (data) {
  19943. return this._buffer.update(data);
  19944. };
  19945. /**
  19946. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19947. * Returns the directly updated WebGLBuffer.
  19948. */
  19949. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19950. return this._buffer.updateDirectly(data, offset);
  19951. };
  19952. /**
  19953. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  19954. */
  19955. VertexBuffer.prototype.dispose = function () {
  19956. if (this._ownsBuffer) {
  19957. this._buffer.dispose();
  19958. }
  19959. };
  19960. Object.defineProperty(VertexBuffer, "PositionKind", {
  19961. get: function () {
  19962. return VertexBuffer._PositionKind;
  19963. },
  19964. enumerable: true,
  19965. configurable: true
  19966. });
  19967. Object.defineProperty(VertexBuffer, "NormalKind", {
  19968. get: function () {
  19969. return VertexBuffer._NormalKind;
  19970. },
  19971. enumerable: true,
  19972. configurable: true
  19973. });
  19974. Object.defineProperty(VertexBuffer, "TangentKind", {
  19975. get: function () {
  19976. return VertexBuffer._TangentKind;
  19977. },
  19978. enumerable: true,
  19979. configurable: true
  19980. });
  19981. Object.defineProperty(VertexBuffer, "UVKind", {
  19982. get: function () {
  19983. return VertexBuffer._UVKind;
  19984. },
  19985. enumerable: true,
  19986. configurable: true
  19987. });
  19988. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19989. get: function () {
  19990. return VertexBuffer._UV2Kind;
  19991. },
  19992. enumerable: true,
  19993. configurable: true
  19994. });
  19995. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19996. get: function () {
  19997. return VertexBuffer._UV3Kind;
  19998. },
  19999. enumerable: true,
  20000. configurable: true
  20001. });
  20002. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20003. get: function () {
  20004. return VertexBuffer._UV4Kind;
  20005. },
  20006. enumerable: true,
  20007. configurable: true
  20008. });
  20009. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20010. get: function () {
  20011. return VertexBuffer._UV5Kind;
  20012. },
  20013. enumerable: true,
  20014. configurable: true
  20015. });
  20016. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20017. get: function () {
  20018. return VertexBuffer._UV6Kind;
  20019. },
  20020. enumerable: true,
  20021. configurable: true
  20022. });
  20023. Object.defineProperty(VertexBuffer, "ColorKind", {
  20024. get: function () {
  20025. return VertexBuffer._ColorKind;
  20026. },
  20027. enumerable: true,
  20028. configurable: true
  20029. });
  20030. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20031. get: function () {
  20032. return VertexBuffer._MatricesIndicesKind;
  20033. },
  20034. enumerable: true,
  20035. configurable: true
  20036. });
  20037. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20038. get: function () {
  20039. return VertexBuffer._MatricesWeightsKind;
  20040. },
  20041. enumerable: true,
  20042. configurable: true
  20043. });
  20044. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20045. get: function () {
  20046. return VertexBuffer._MatricesIndicesExtraKind;
  20047. },
  20048. enumerable: true,
  20049. configurable: true
  20050. });
  20051. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20052. get: function () {
  20053. return VertexBuffer._MatricesWeightsExtraKind;
  20054. },
  20055. enumerable: true,
  20056. configurable: true
  20057. });
  20058. // Enums
  20059. VertexBuffer._PositionKind = "position";
  20060. VertexBuffer._NormalKind = "normal";
  20061. VertexBuffer._TangentKind = "tangent";
  20062. VertexBuffer._UVKind = "uv";
  20063. VertexBuffer._UV2Kind = "uv2";
  20064. VertexBuffer._UV3Kind = "uv3";
  20065. VertexBuffer._UV4Kind = "uv4";
  20066. VertexBuffer._UV5Kind = "uv5";
  20067. VertexBuffer._UV6Kind = "uv6";
  20068. VertexBuffer._ColorKind = "color";
  20069. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20070. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20071. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20072. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20073. return VertexBuffer;
  20074. }());
  20075. BABYLON.VertexBuffer = VertexBuffer;
  20076. })(BABYLON || (BABYLON = {}));
  20077. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20078. var BABYLON;
  20079. (function (BABYLON) {
  20080. var InternalTexture = (function () {
  20081. function InternalTexture(engine, dataSource) {
  20082. this.onLoadedObservable = new BABYLON.Observable();
  20083. // Private
  20084. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  20085. this._references = 1;
  20086. this._engine = engine;
  20087. this._dataSource = dataSource;
  20088. this._webGLTexture = engine._createTexture();
  20089. }
  20090. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  20091. get: function () {
  20092. return this._dataSource;
  20093. },
  20094. enumerable: true,
  20095. configurable: true
  20096. });
  20097. InternalTexture.prototype.incrementReferences = function () {
  20098. this._references++;
  20099. };
  20100. InternalTexture.prototype.updateSize = function (width, height) {
  20101. this.width = width;
  20102. this.height = height;
  20103. this._size = width * height;
  20104. this.baseWidth = width;
  20105. this.baseHeight = height;
  20106. };
  20107. InternalTexture.prototype._rebuild = function () {
  20108. var _this = this;
  20109. var proxy;
  20110. this.isReady = false;
  20111. this._cachedCoordinatesMode = null;
  20112. this._cachedWrapU = null;
  20113. this._cachedWrapV = null;
  20114. this._cachedAnisotropicFilteringLevel = null;
  20115. switch (this._dataSource) {
  20116. case InternalTexture.DATASOURCE_TEMP:
  20117. return;
  20118. case InternalTexture.DATASOURCE_URL:
  20119. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  20120. _this.isReady = true;
  20121. }, null, this._buffer, null, this.format);
  20122. proxy._swapAndDie(this);
  20123. return;
  20124. case InternalTexture.DATASOURCE_RAW:
  20125. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20126. proxy._swapAndDie(this);
  20127. this.isReady = true;
  20128. return;
  20129. case InternalTexture.DATASOURCE_DYNAMIC:
  20130. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  20131. proxy._swapAndDie(this);
  20132. // The engine will make sure to update content so no need to flag it as isReady = true
  20133. return;
  20134. case InternalTexture.DATASOURCE_RENDERTARGET:
  20135. var options = new BABYLON.RenderTargetCreationOptions();
  20136. options.generateDepthBuffer = this._generateDepthBuffer;
  20137. options.generateMipMaps = this.generateMipMaps;
  20138. options.generateStencilBuffer = this._generateStencilBuffer;
  20139. options.samplingMode = this.samplingMode;
  20140. options.type = this.type;
  20141. if (this.isCube) {
  20142. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20143. }
  20144. else {
  20145. var size = {
  20146. width: this.width,
  20147. height: this.height
  20148. };
  20149. proxy = this._engine.createRenderTargetTexture(size, options);
  20150. }
  20151. proxy._swapAndDie(this);
  20152. this.isReady = true;
  20153. return;
  20154. case InternalTexture.DATASOURCE_CUBE:
  20155. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20156. _this.isReady = true;
  20157. }, null, this.format, this._extension);
  20158. proxy._swapAndDie(this);
  20159. return;
  20160. case InternalTexture.DATASOURCE_CUBERAW:
  20161. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20162. proxy._swapAndDie(this);
  20163. this.isReady = true;
  20164. return;
  20165. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20166. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20167. proxy._swapAndDie(_this);
  20168. _this.isReady = true;
  20169. }, null, this.format, this._extension);
  20170. return;
  20171. }
  20172. };
  20173. InternalTexture.prototype._swapAndDie = function (target) {
  20174. target._webGLTexture = this._webGLTexture;
  20175. if (this._framebuffer) {
  20176. target._framebuffer = this._framebuffer;
  20177. }
  20178. if (this._depthStencilBuffer) {
  20179. target._depthStencilBuffer = this._depthStencilBuffer;
  20180. }
  20181. if (this._lodTextureHigh) {
  20182. if (target._lodTextureHigh) {
  20183. target._lodTextureHigh.dispose();
  20184. }
  20185. target._lodTextureHigh = this._lodTextureHigh;
  20186. }
  20187. if (this._lodTextureMid) {
  20188. if (target._lodTextureMid) {
  20189. target._lodTextureMid.dispose();
  20190. }
  20191. target._lodTextureMid = this._lodTextureMid;
  20192. }
  20193. if (this._lodTextureLow) {
  20194. if (target._lodTextureLow) {
  20195. target._lodTextureLow.dispose();
  20196. }
  20197. target._lodTextureLow = this._lodTextureLow;
  20198. }
  20199. var cache = this._engine.getLoadedTexturesCache();
  20200. var index = cache.indexOf(this);
  20201. if (index !== -1) {
  20202. cache.splice(index, 1);
  20203. }
  20204. };
  20205. InternalTexture.prototype.dispose = function () {
  20206. if (!this._webGLTexture) {
  20207. return;
  20208. }
  20209. this._references--;
  20210. if (this._references === 0) {
  20211. this._engine._releaseTexture(this);
  20212. this._webGLTexture = null;
  20213. }
  20214. };
  20215. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20216. InternalTexture.DATASOURCE_URL = 1;
  20217. InternalTexture.DATASOURCE_TEMP = 2;
  20218. InternalTexture.DATASOURCE_RAW = 3;
  20219. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20220. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20221. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20222. InternalTexture.DATASOURCE_CUBE = 7;
  20223. InternalTexture.DATASOURCE_CUBERAW = 8;
  20224. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20225. return InternalTexture;
  20226. }());
  20227. BABYLON.InternalTexture = InternalTexture;
  20228. })(BABYLON || (BABYLON = {}));
  20229. //# sourceMappingURL=babylon.internalTexture.js.map
  20230. var BABYLON;
  20231. (function (BABYLON) {
  20232. var BaseTexture = (function () {
  20233. function BaseTexture(scene) {
  20234. this._hasAlpha = false;
  20235. this.getAlphaFromRGB = false;
  20236. this.level = 1;
  20237. this.coordinatesIndex = 0;
  20238. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20239. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20240. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20241. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20242. this.isCube = false;
  20243. this.gammaSpace = true;
  20244. this.invertZ = false;
  20245. this.lodLevelInAlpha = false;
  20246. this.lodGenerationOffset = 0.0;
  20247. this.lodGenerationScale = 0.8;
  20248. this.isRenderTarget = false;
  20249. this.animations = new Array();
  20250. /**
  20251. * An event triggered when the texture is disposed.
  20252. * @type {BABYLON.Observable}
  20253. */
  20254. this.onDisposeObservable = new BABYLON.Observable();
  20255. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20256. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20257. this._scene.textures.push(this);
  20258. this._uid = null;
  20259. }
  20260. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20261. get: function () {
  20262. return this._hasAlpha;
  20263. },
  20264. set: function (value) {
  20265. if (this._hasAlpha === value) {
  20266. return;
  20267. }
  20268. this._hasAlpha = value;
  20269. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20270. },
  20271. enumerable: true,
  20272. configurable: true
  20273. });
  20274. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20275. get: function () {
  20276. return this._coordinatesMode;
  20277. },
  20278. set: function (value) {
  20279. if (this._coordinatesMode === value) {
  20280. return;
  20281. }
  20282. this._coordinatesMode = value;
  20283. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20284. },
  20285. enumerable: true,
  20286. configurable: true
  20287. });
  20288. Object.defineProperty(BaseTexture.prototype, "uid", {
  20289. get: function () {
  20290. if (!this._uid) {
  20291. this._uid = BABYLON.Tools.RandomId();
  20292. }
  20293. return this._uid;
  20294. },
  20295. enumerable: true,
  20296. configurable: true
  20297. });
  20298. BaseTexture.prototype.toString = function () {
  20299. return this.name;
  20300. };
  20301. BaseTexture.prototype.getClassName = function () {
  20302. return "BaseTexture";
  20303. };
  20304. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20305. set: function (callback) {
  20306. if (this._onDisposeObserver) {
  20307. this.onDisposeObservable.remove(this._onDisposeObserver);
  20308. }
  20309. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20310. },
  20311. enumerable: true,
  20312. configurable: true
  20313. });
  20314. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20315. get: function () {
  20316. return true;
  20317. },
  20318. enumerable: true,
  20319. configurable: true
  20320. });
  20321. BaseTexture.prototype.getScene = function () {
  20322. return this._scene;
  20323. };
  20324. BaseTexture.prototype.getTextureMatrix = function () {
  20325. return null;
  20326. };
  20327. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20328. return null;
  20329. };
  20330. BaseTexture.prototype.getInternalTexture = function () {
  20331. return this._texture;
  20332. };
  20333. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20334. return !this.isBlocking || this.isReady();
  20335. };
  20336. BaseTexture.prototype.isReady = function () {
  20337. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20338. this.delayLoad();
  20339. return false;
  20340. }
  20341. if (this._texture) {
  20342. return this._texture.isReady;
  20343. }
  20344. return false;
  20345. };
  20346. BaseTexture.prototype.getSize = function () {
  20347. if (this._texture.width) {
  20348. return new BABYLON.Size(this._texture.width, this._texture.height);
  20349. }
  20350. if (this._texture._size) {
  20351. return new BABYLON.Size(this._texture._size, this._texture._size);
  20352. }
  20353. return BABYLON.Size.Zero();
  20354. };
  20355. BaseTexture.prototype.getBaseSize = function () {
  20356. if (!this.isReady() || !this._texture)
  20357. return BABYLON.Size.Zero();
  20358. if (this._texture._size) {
  20359. return new BABYLON.Size(this._texture._size, this._texture._size);
  20360. }
  20361. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20362. };
  20363. BaseTexture.prototype.scale = function (ratio) {
  20364. };
  20365. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20366. get: function () {
  20367. return false;
  20368. },
  20369. enumerable: true,
  20370. configurable: true
  20371. });
  20372. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20373. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20374. for (var index = 0; index < texturesCache.length; index++) {
  20375. var texturesCacheEntry = texturesCache[index];
  20376. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20377. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20378. texturesCacheEntry.incrementReferences();
  20379. return texturesCacheEntry;
  20380. }
  20381. }
  20382. }
  20383. return null;
  20384. };
  20385. BaseTexture.prototype._rebuild = function () {
  20386. };
  20387. BaseTexture.prototype.delayLoad = function () {
  20388. };
  20389. BaseTexture.prototype.clone = function () {
  20390. return null;
  20391. };
  20392. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20393. get: function () {
  20394. if (!this._texture) {
  20395. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20396. }
  20397. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20398. },
  20399. enumerable: true,
  20400. configurable: true
  20401. });
  20402. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20403. get: function () {
  20404. if (!this._texture) {
  20405. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20406. }
  20407. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20408. },
  20409. enumerable: true,
  20410. configurable: true
  20411. });
  20412. BaseTexture.prototype.readPixels = function (faceIndex) {
  20413. if (faceIndex === void 0) { faceIndex = 0; }
  20414. if (!this._texture) {
  20415. return null;
  20416. }
  20417. var size = this.getSize();
  20418. var engine = this.getScene().getEngine();
  20419. if (this._texture.isCube) {
  20420. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20421. }
  20422. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20423. };
  20424. BaseTexture.prototype.releaseInternalTexture = function () {
  20425. if (this._texture) {
  20426. this._texture.dispose();
  20427. this._texture = null;
  20428. }
  20429. };
  20430. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20431. get: function () {
  20432. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20433. return null;
  20434. }
  20435. if (!this._texture._sphericalPolynomial) {
  20436. this._texture._sphericalPolynomial =
  20437. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20438. }
  20439. return this._texture._sphericalPolynomial;
  20440. },
  20441. set: function (value) {
  20442. if (this._texture) {
  20443. this._texture._sphericalPolynomial = value;
  20444. }
  20445. },
  20446. enumerable: true,
  20447. configurable: true
  20448. });
  20449. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20450. get: function () {
  20451. if (this._texture) {
  20452. return this._texture._lodTextureHigh;
  20453. }
  20454. return null;
  20455. },
  20456. enumerable: true,
  20457. configurable: true
  20458. });
  20459. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20460. get: function () {
  20461. if (this._texture) {
  20462. return this._texture._lodTextureMid;
  20463. }
  20464. return null;
  20465. },
  20466. enumerable: true,
  20467. configurable: true
  20468. });
  20469. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20470. get: function () {
  20471. if (this._texture) {
  20472. return this._texture._lodTextureLow;
  20473. }
  20474. return null;
  20475. },
  20476. enumerable: true,
  20477. configurable: true
  20478. });
  20479. BaseTexture.prototype.dispose = function () {
  20480. // Animations
  20481. this.getScene().stopAnimation(this);
  20482. // Remove from scene
  20483. this._scene._removePendingData(this);
  20484. var index = this._scene.textures.indexOf(this);
  20485. if (index >= 0) {
  20486. this._scene.textures.splice(index, 1);
  20487. }
  20488. if (this._texture === undefined) {
  20489. return;
  20490. }
  20491. // Release
  20492. this.releaseInternalTexture();
  20493. // Callback
  20494. this.onDisposeObservable.notifyObservers(this);
  20495. this.onDisposeObservable.clear();
  20496. };
  20497. BaseTexture.prototype.serialize = function () {
  20498. if (!this.name) {
  20499. return null;
  20500. }
  20501. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20502. // Animations
  20503. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20504. return serializationObject;
  20505. };
  20506. BaseTexture.WhenAllReady = function (textures, callback) {
  20507. var numRemaining = textures.length;
  20508. if (numRemaining === 0) {
  20509. callback();
  20510. return;
  20511. }
  20512. var _loop_1 = function () {
  20513. texture = textures[i];
  20514. if (texture.isReady()) {
  20515. if (--numRemaining === 0) {
  20516. callback();
  20517. }
  20518. }
  20519. else {
  20520. onLoadObservable = texture.onLoadObservable;
  20521. var onLoadCallback_1 = function () {
  20522. onLoadObservable.removeCallback(onLoadCallback_1);
  20523. if (--numRemaining === 0) {
  20524. callback();
  20525. }
  20526. };
  20527. onLoadObservable.add(onLoadCallback_1);
  20528. }
  20529. };
  20530. var texture, onLoadObservable;
  20531. for (var i = 0; i < textures.length; i++) {
  20532. _loop_1();
  20533. }
  20534. };
  20535. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20536. __decorate([
  20537. BABYLON.serialize()
  20538. ], BaseTexture.prototype, "name", void 0);
  20539. __decorate([
  20540. BABYLON.serialize("hasAlpha")
  20541. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20542. __decorate([
  20543. BABYLON.serialize()
  20544. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20545. __decorate([
  20546. BABYLON.serialize()
  20547. ], BaseTexture.prototype, "level", void 0);
  20548. __decorate([
  20549. BABYLON.serialize()
  20550. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20551. __decorate([
  20552. BABYLON.serialize("coordinatesMode")
  20553. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20554. __decorate([
  20555. BABYLON.serialize()
  20556. ], BaseTexture.prototype, "wrapU", void 0);
  20557. __decorate([
  20558. BABYLON.serialize()
  20559. ], BaseTexture.prototype, "wrapV", void 0);
  20560. __decorate([
  20561. BABYLON.serialize()
  20562. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20563. __decorate([
  20564. BABYLON.serialize()
  20565. ], BaseTexture.prototype, "isCube", void 0);
  20566. __decorate([
  20567. BABYLON.serialize()
  20568. ], BaseTexture.prototype, "gammaSpace", void 0);
  20569. __decorate([
  20570. BABYLON.serialize()
  20571. ], BaseTexture.prototype, "invertZ", void 0);
  20572. __decorate([
  20573. BABYLON.serialize()
  20574. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20575. __decorate([
  20576. BABYLON.serialize()
  20577. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20578. __decorate([
  20579. BABYLON.serialize()
  20580. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20581. __decorate([
  20582. BABYLON.serialize()
  20583. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20584. return BaseTexture;
  20585. }());
  20586. BABYLON.BaseTexture = BaseTexture;
  20587. })(BABYLON || (BABYLON = {}));
  20588. //# sourceMappingURL=babylon.baseTexture.js.map
  20589. var BABYLON;
  20590. (function (BABYLON) {
  20591. var Texture = (function (_super) {
  20592. __extends(Texture, _super);
  20593. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20594. if (noMipmap === void 0) { noMipmap = false; }
  20595. if (invertY === void 0) { invertY = true; }
  20596. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20597. if (onLoad === void 0) { onLoad = null; }
  20598. if (onError === void 0) { onError = null; }
  20599. if (buffer === void 0) { buffer = null; }
  20600. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20601. var _this = _super.call(this, scene) || this;
  20602. _this.uOffset = 0;
  20603. _this.vOffset = 0;
  20604. _this.uScale = 1.0;
  20605. _this.vScale = 1.0;
  20606. _this.uAng = 0;
  20607. _this.vAng = 0;
  20608. _this.wAng = 0;
  20609. _this._isBlocking = true;
  20610. _this.name = url;
  20611. _this.url = url;
  20612. _this._noMipmap = noMipmap;
  20613. _this._invertY = invertY;
  20614. _this._samplingMode = samplingMode;
  20615. _this._buffer = buffer;
  20616. _this._deleteBuffer = deleteBuffer;
  20617. _this._format = format;
  20618. scene = _this.getScene();
  20619. var load = function () {
  20620. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20621. _this.onLoadObservable.notifyObservers(_this);
  20622. }
  20623. if (onLoad) {
  20624. onLoad();
  20625. }
  20626. if (!_this.isBlocking) {
  20627. scene.resetCachedMaterial();
  20628. }
  20629. };
  20630. if (!url) {
  20631. _this._delayedOnLoad = load;
  20632. _this._delayedOnError = onError;
  20633. return _this;
  20634. }
  20635. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  20636. if (!_this._texture) {
  20637. if (!scene.useDelayedTextureLoading) {
  20638. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20639. if (deleteBuffer) {
  20640. delete _this._buffer;
  20641. }
  20642. }
  20643. else {
  20644. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20645. _this._delayedOnLoad = load;
  20646. _this._delayedOnError = onError;
  20647. }
  20648. }
  20649. else {
  20650. if (_this._texture.isReady) {
  20651. BABYLON.Tools.SetImmediate(function () { return load(); });
  20652. }
  20653. else {
  20654. _this._texture.onLoadedObservable.add(load);
  20655. }
  20656. }
  20657. return _this;
  20658. }
  20659. Object.defineProperty(Texture.prototype, "noMipmap", {
  20660. get: function () {
  20661. return this._noMipmap;
  20662. },
  20663. enumerable: true,
  20664. configurable: true
  20665. });
  20666. Object.defineProperty(Texture.prototype, "isBlocking", {
  20667. get: function () {
  20668. return this._isBlocking;
  20669. },
  20670. set: function (value) {
  20671. this._isBlocking = value;
  20672. },
  20673. enumerable: true,
  20674. configurable: true
  20675. });
  20676. Object.defineProperty(Texture.prototype, "samplingMode", {
  20677. get: function () {
  20678. return this._samplingMode;
  20679. },
  20680. enumerable: true,
  20681. configurable: true
  20682. });
  20683. Texture.prototype.updateURL = function (url) {
  20684. this.url = url;
  20685. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20686. this.delayLoad();
  20687. };
  20688. Texture.prototype.delayLoad = function () {
  20689. var _this = this;
  20690. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20691. return;
  20692. }
  20693. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20694. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20695. if (!this._texture) {
  20696. 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);
  20697. if (this._deleteBuffer) {
  20698. delete this._buffer;
  20699. }
  20700. }
  20701. else {
  20702. if (this._texture.isReady) {
  20703. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20704. }
  20705. else {
  20706. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  20707. }
  20708. }
  20709. };
  20710. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20711. if (!this._texture) {
  20712. return;
  20713. }
  20714. this._samplingMode = samplingMode;
  20715. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20716. };
  20717. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20718. x *= this.uScale;
  20719. y *= this.vScale;
  20720. x -= 0.5 * this.uScale;
  20721. y -= 0.5 * this.vScale;
  20722. z -= 0.5;
  20723. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20724. t.x += 0.5 * this.uScale + this.uOffset;
  20725. t.y += 0.5 * this.vScale + this.vOffset;
  20726. t.z += 0.5;
  20727. };
  20728. Texture.prototype.getTextureMatrix = function () {
  20729. var _this = this;
  20730. if (this.uOffset === this._cachedUOffset &&
  20731. this.vOffset === this._cachedVOffset &&
  20732. this.uScale === this._cachedUScale &&
  20733. this.vScale === this._cachedVScale &&
  20734. this.uAng === this._cachedUAng &&
  20735. this.vAng === this._cachedVAng &&
  20736. this.wAng === this._cachedWAng) {
  20737. return this._cachedTextureMatrix;
  20738. }
  20739. this._cachedUOffset = this.uOffset;
  20740. this._cachedVOffset = this.vOffset;
  20741. this._cachedUScale = this.uScale;
  20742. this._cachedVScale = this.vScale;
  20743. this._cachedUAng = this.uAng;
  20744. this._cachedVAng = this.vAng;
  20745. this._cachedWAng = this.wAng;
  20746. if (!this._cachedTextureMatrix) {
  20747. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20748. this._rowGenerationMatrix = new BABYLON.Matrix();
  20749. this._t0 = BABYLON.Vector3.Zero();
  20750. this._t1 = BABYLON.Vector3.Zero();
  20751. this._t2 = BABYLON.Vector3.Zero();
  20752. }
  20753. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20754. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20755. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20756. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20757. this._t1.subtractInPlace(this._t0);
  20758. this._t2.subtractInPlace(this._t0);
  20759. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20760. this._cachedTextureMatrix.m[0] = this._t1.x;
  20761. this._cachedTextureMatrix.m[1] = this._t1.y;
  20762. this._cachedTextureMatrix.m[2] = this._t1.z;
  20763. this._cachedTextureMatrix.m[4] = this._t2.x;
  20764. this._cachedTextureMatrix.m[5] = this._t2.y;
  20765. this._cachedTextureMatrix.m[6] = this._t2.z;
  20766. this._cachedTextureMatrix.m[8] = this._t0.x;
  20767. this._cachedTextureMatrix.m[9] = this._t0.y;
  20768. this._cachedTextureMatrix.m[10] = this._t0.z;
  20769. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20770. return mat.hasTexture(_this);
  20771. });
  20772. return this._cachedTextureMatrix;
  20773. };
  20774. Texture.prototype.getReflectionTextureMatrix = function () {
  20775. var _this = this;
  20776. var scene = this.getScene();
  20777. if (this.uOffset === this._cachedUOffset &&
  20778. this.vOffset === this._cachedVOffset &&
  20779. this.uScale === this._cachedUScale &&
  20780. this.vScale === this._cachedVScale &&
  20781. this.coordinatesMode === this._cachedCoordinatesMode) {
  20782. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  20783. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  20784. return this._cachedTextureMatrix;
  20785. }
  20786. }
  20787. else {
  20788. return this._cachedTextureMatrix;
  20789. }
  20790. }
  20791. if (!this._cachedTextureMatrix) {
  20792. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20793. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20794. }
  20795. this._cachedUOffset = this.uOffset;
  20796. this._cachedVOffset = this.vOffset;
  20797. this._cachedUScale = this.uScale;
  20798. this._cachedVScale = this.vScale;
  20799. this._cachedCoordinatesMode = this.coordinatesMode;
  20800. switch (this.coordinatesMode) {
  20801. case Texture.PLANAR_MODE:
  20802. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20803. this._cachedTextureMatrix[0] = this.uScale;
  20804. this._cachedTextureMatrix[5] = this.vScale;
  20805. this._cachedTextureMatrix[12] = this.uOffset;
  20806. this._cachedTextureMatrix[13] = this.vOffset;
  20807. break;
  20808. case Texture.PROJECTION_MODE:
  20809. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20810. this._projectionModeMatrix.m[0] = 0.5;
  20811. this._projectionModeMatrix.m[5] = -0.5;
  20812. this._projectionModeMatrix.m[10] = 0.0;
  20813. this._projectionModeMatrix.m[12] = 0.5;
  20814. this._projectionModeMatrix.m[13] = 0.5;
  20815. this._projectionModeMatrix.m[14] = 1.0;
  20816. this._projectionModeMatrix.m[15] = 1.0;
  20817. var projectionMatrix = scene.getProjectionMatrix();
  20818. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  20819. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20820. break;
  20821. default:
  20822. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20823. break;
  20824. }
  20825. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20826. return (mat.getActiveTextures().indexOf(_this) !== -1);
  20827. });
  20828. return this._cachedTextureMatrix;
  20829. };
  20830. Texture.prototype.clone = function () {
  20831. var _this = this;
  20832. return BABYLON.SerializationHelper.Clone(function () {
  20833. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20834. }, this);
  20835. };
  20836. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  20837. get: function () {
  20838. if (!this._onLoadObservable) {
  20839. this._onLoadObservable = new BABYLON.Observable();
  20840. }
  20841. return this._onLoadObservable;
  20842. },
  20843. enumerable: true,
  20844. configurable: true
  20845. });
  20846. Texture.prototype.serialize = function () {
  20847. var serializationObject = _super.prototype.serialize.call(this);
  20848. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  20849. serializationObject.base64String = this._buffer;
  20850. serializationObject.name = serializationObject.name.replace("data:", "");
  20851. }
  20852. return serializationObject;
  20853. };
  20854. Texture.prototype.getClassName = function () {
  20855. return "Texture";
  20856. };
  20857. Texture.prototype.dispose = function () {
  20858. _super.prototype.dispose.call(this);
  20859. if (this.onLoadObservable) {
  20860. this.onLoadObservable.clear();
  20861. this._onLoadObservable = null;
  20862. }
  20863. this._delayedOnLoad = null;
  20864. this._delayedOnError = null;
  20865. };
  20866. // Statics
  20867. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20868. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20869. if (onLoad === void 0) { onLoad = null; }
  20870. if (onError === void 0) { onError = null; }
  20871. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20872. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  20873. };
  20874. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20875. if (parsedTexture.customType) {
  20876. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  20877. // Update Sampling Mode
  20878. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  20879. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  20880. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  20881. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  20882. }
  20883. }
  20884. return parsedCustomTexture;
  20885. }
  20886. if (parsedTexture.isCube) {
  20887. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20888. }
  20889. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20890. return null;
  20891. }
  20892. var texture = BABYLON.SerializationHelper.Parse(function () {
  20893. if (parsedTexture.mirrorPlane) {
  20894. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20895. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20896. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20897. return mirrorTexture;
  20898. }
  20899. else if (parsedTexture.isRenderTarget) {
  20900. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20901. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20902. return renderTargetTexture;
  20903. }
  20904. else {
  20905. var texture;
  20906. if (parsedTexture.base64String) {
  20907. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20908. }
  20909. else {
  20910. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20911. }
  20912. return texture;
  20913. }
  20914. }, parsedTexture, scene);
  20915. // Update Sampling Mode
  20916. if (parsedTexture.samplingMode) {
  20917. var sampling = parsedTexture.samplingMode;
  20918. if (texture._samplingMode !== sampling) {
  20919. texture.updateSamplingMode(sampling);
  20920. }
  20921. }
  20922. // Animations
  20923. if (parsedTexture.animations) {
  20924. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20925. var parsedAnimation = parsedTexture.animations[animationIndex];
  20926. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20927. }
  20928. }
  20929. return texture;
  20930. };
  20931. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20932. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20933. if (noMipmap === void 0) { noMipmap = false; }
  20934. if (invertY === void 0) { invertY = true; }
  20935. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20936. if (onLoad === void 0) { onLoad = null; }
  20937. if (onError === void 0) { onError = null; }
  20938. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20939. if (name.substr(0, 5) !== "data:") {
  20940. name = "data:" + name;
  20941. }
  20942. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  20943. };
  20944. // Constants
  20945. Texture.NEAREST_SAMPLINGMODE = 1;
  20946. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  20947. Texture.BILINEAR_SAMPLINGMODE = 2;
  20948. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  20949. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20950. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  20951. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  20952. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  20953. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  20954. Texture.NEAREST_LINEAR = 7;
  20955. Texture.NEAREST_NEAREST = 8;
  20956. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  20957. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  20958. Texture.LINEAR_LINEAR = 11;
  20959. Texture.LINEAR_NEAREST = 12;
  20960. Texture.EXPLICIT_MODE = 0;
  20961. Texture.SPHERICAL_MODE = 1;
  20962. Texture.PLANAR_MODE = 2;
  20963. Texture.CUBIC_MODE = 3;
  20964. Texture.PROJECTION_MODE = 4;
  20965. Texture.SKYBOX_MODE = 5;
  20966. Texture.INVCUBIC_MODE = 6;
  20967. Texture.EQUIRECTANGULAR_MODE = 7;
  20968. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20969. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  20970. Texture.CLAMP_ADDRESSMODE = 0;
  20971. Texture.WRAP_ADDRESSMODE = 1;
  20972. Texture.MIRROR_ADDRESSMODE = 2;
  20973. __decorate([
  20974. BABYLON.serialize()
  20975. ], Texture.prototype, "url", void 0);
  20976. __decorate([
  20977. BABYLON.serialize()
  20978. ], Texture.prototype, "uOffset", void 0);
  20979. __decorate([
  20980. BABYLON.serialize()
  20981. ], Texture.prototype, "vOffset", void 0);
  20982. __decorate([
  20983. BABYLON.serialize()
  20984. ], Texture.prototype, "uScale", void 0);
  20985. __decorate([
  20986. BABYLON.serialize()
  20987. ], Texture.prototype, "vScale", void 0);
  20988. __decorate([
  20989. BABYLON.serialize()
  20990. ], Texture.prototype, "uAng", void 0);
  20991. __decorate([
  20992. BABYLON.serialize()
  20993. ], Texture.prototype, "vAng", void 0);
  20994. __decorate([
  20995. BABYLON.serialize()
  20996. ], Texture.prototype, "wAng", void 0);
  20997. __decorate([
  20998. BABYLON.serialize()
  20999. ], Texture.prototype, "isBlocking", null);
  21000. return Texture;
  21001. }(BABYLON.BaseTexture));
  21002. BABYLON.Texture = Texture;
  21003. })(BABYLON || (BABYLON = {}));
  21004. //# sourceMappingURL=babylon.texture.js.map
  21005. var BABYLON;
  21006. (function (BABYLON) {
  21007. var _InstancesBatch = (function () {
  21008. function _InstancesBatch() {
  21009. this.mustReturn = false;
  21010. this.visibleInstances = new Array();
  21011. this.renderSelf = new Array();
  21012. }
  21013. return _InstancesBatch;
  21014. }());
  21015. BABYLON._InstancesBatch = _InstancesBatch;
  21016. var Mesh = (function (_super) {
  21017. __extends(Mesh, _super);
  21018. /**
  21019. * @constructor
  21020. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  21021. * @param {Scene} scene The scene to add this mesh to.
  21022. * @param {Node} parent The parent of this mesh, if it has one
  21023. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  21024. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  21025. * When false, achieved by calling a clone(), also passing False.
  21026. * This will make creation of children, recursive.
  21027. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  21028. */
  21029. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  21030. if (parent === void 0) { parent = null; }
  21031. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21032. var _this = _super.call(this, name, scene) || this;
  21033. // Events
  21034. /**
  21035. * An event triggered before rendering the mesh
  21036. * @type {BABYLON.Observable}
  21037. */
  21038. _this.onBeforeRenderObservable = new BABYLON.Observable();
  21039. /**
  21040. * An event triggered after rendering the mesh
  21041. * @type {BABYLON.Observable}
  21042. */
  21043. _this.onAfterRenderObservable = new BABYLON.Observable();
  21044. /**
  21045. * An event triggered before drawing the mesh
  21046. * @type {BABYLON.Observable}
  21047. */
  21048. _this.onBeforeDrawObservable = new BABYLON.Observable();
  21049. // Members
  21050. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21051. _this.instances = new Array();
  21052. _this._LODLevels = new Array();
  21053. _this._visibleInstances = {};
  21054. _this._renderIdForInstances = new Array();
  21055. _this._batchCache = new _InstancesBatch();
  21056. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  21057. _this._sideOrientation = Mesh._DEFAULTSIDE;
  21058. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  21059. // Will be used to save a source mesh reference, If any
  21060. _this._source = null;
  21061. if (source) {
  21062. // Source mesh
  21063. _this._source = source;
  21064. // Geometry
  21065. if (source._geometry) {
  21066. source._geometry.applyToMesh(_this);
  21067. }
  21068. // Deep copy
  21069. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  21070. // Parent
  21071. _this.parent = source.parent;
  21072. // Pivot
  21073. _this.setPivotMatrix(source.getPivotMatrix());
  21074. _this.id = name + "." + source.id;
  21075. // Material
  21076. _this.material = source.material;
  21077. var index;
  21078. if (!doNotCloneChildren) {
  21079. // Children
  21080. for (index = 0; index < scene.meshes.length; index++) {
  21081. var mesh = scene.meshes[index];
  21082. if (mesh.parent === source) {
  21083. // doNotCloneChildren is always going to be False
  21084. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  21085. }
  21086. }
  21087. }
  21088. // Physics clone
  21089. var physicsEngine = _this.getScene().getPhysicsEngine();
  21090. if (clonePhysicsImpostor && physicsEngine) {
  21091. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  21092. if (impostor) {
  21093. _this.physicsImpostor = impostor.clone(_this);
  21094. }
  21095. }
  21096. // Particles
  21097. for (index = 0; index < scene.particleSystems.length; index++) {
  21098. var system = scene.particleSystems[index];
  21099. if (system.emitter === source) {
  21100. system.clone(system.name, _this);
  21101. }
  21102. }
  21103. _this.computeWorldMatrix(true);
  21104. }
  21105. // Parent
  21106. if (parent !== null) {
  21107. _this.parent = parent;
  21108. }
  21109. return _this;
  21110. }
  21111. Object.defineProperty(Mesh, "FRONTSIDE", {
  21112. /**
  21113. * Mesh side orientation : usually the external or front surface
  21114. */
  21115. get: function () {
  21116. return Mesh._FRONTSIDE;
  21117. },
  21118. enumerable: true,
  21119. configurable: true
  21120. });
  21121. Object.defineProperty(Mesh, "BACKSIDE", {
  21122. /**
  21123. * Mesh side orientation : usually the internal or back surface
  21124. */
  21125. get: function () {
  21126. return Mesh._BACKSIDE;
  21127. },
  21128. enumerable: true,
  21129. configurable: true
  21130. });
  21131. Object.defineProperty(Mesh, "DOUBLESIDE", {
  21132. /**
  21133. * Mesh side orientation : both internal and external or front and back surfaces
  21134. */
  21135. get: function () {
  21136. return Mesh._DOUBLESIDE;
  21137. },
  21138. enumerable: true,
  21139. configurable: true
  21140. });
  21141. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  21142. /**
  21143. * Mesh side orientation : by default, `FRONTSIDE`
  21144. */
  21145. get: function () {
  21146. return Mesh._DEFAULTSIDE;
  21147. },
  21148. enumerable: true,
  21149. configurable: true
  21150. });
  21151. Object.defineProperty(Mesh, "NO_CAP", {
  21152. /**
  21153. * Mesh cap setting : no cap
  21154. */
  21155. get: function () {
  21156. return Mesh._NO_CAP;
  21157. },
  21158. enumerable: true,
  21159. configurable: true
  21160. });
  21161. Object.defineProperty(Mesh, "CAP_START", {
  21162. /**
  21163. * Mesh cap setting : one cap at the beginning of the mesh
  21164. */
  21165. get: function () {
  21166. return Mesh._CAP_START;
  21167. },
  21168. enumerable: true,
  21169. configurable: true
  21170. });
  21171. Object.defineProperty(Mesh, "CAP_END", {
  21172. /**
  21173. * Mesh cap setting : one cap at the end of the mesh
  21174. */
  21175. get: function () {
  21176. return Mesh._CAP_END;
  21177. },
  21178. enumerable: true,
  21179. configurable: true
  21180. });
  21181. Object.defineProperty(Mesh, "CAP_ALL", {
  21182. /**
  21183. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21184. */
  21185. get: function () {
  21186. return Mesh._CAP_ALL;
  21187. },
  21188. enumerable: true,
  21189. configurable: true
  21190. });
  21191. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21192. set: function (callback) {
  21193. if (this._onBeforeDrawObserver) {
  21194. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21195. }
  21196. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21197. },
  21198. enumerable: true,
  21199. configurable: true
  21200. });
  21201. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21202. get: function () {
  21203. return this._morphTargetManager;
  21204. },
  21205. set: function (value) {
  21206. if (this._morphTargetManager === value) {
  21207. return;
  21208. }
  21209. this._morphTargetManager = value;
  21210. this._syncGeometryWithMorphTargetManager();
  21211. },
  21212. enumerable: true,
  21213. configurable: true
  21214. });
  21215. Object.defineProperty(Mesh.prototype, "source", {
  21216. get: function () {
  21217. return this._source;
  21218. },
  21219. enumerable: true,
  21220. configurable: true
  21221. });
  21222. // Methods
  21223. /**
  21224. * Returns the string "Mesh".
  21225. */
  21226. Mesh.prototype.getClassName = function () {
  21227. return "Mesh";
  21228. };
  21229. /**
  21230. * Returns a string.
  21231. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21232. */
  21233. Mesh.prototype.toString = function (fullDetails) {
  21234. var ret = _super.prototype.toString.call(this, fullDetails);
  21235. ret += ", n vertices: " + this.getTotalVertices();
  21236. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21237. if (this.animations) {
  21238. for (var i = 0; i < this.animations.length; i++) {
  21239. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21240. }
  21241. }
  21242. if (fullDetails) {
  21243. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21244. }
  21245. return ret;
  21246. };
  21247. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21248. /**
  21249. * True if the mesh has some Levels Of Details (LOD).
  21250. * Returns a boolean.
  21251. */
  21252. get: function () {
  21253. return this._LODLevels.length > 0;
  21254. },
  21255. enumerable: true,
  21256. configurable: true
  21257. });
  21258. Mesh.prototype._sortLODLevels = function () {
  21259. this._LODLevels.sort(function (a, b) {
  21260. if (a.distance < b.distance) {
  21261. return 1;
  21262. }
  21263. if (a.distance > b.distance) {
  21264. return -1;
  21265. }
  21266. return 0;
  21267. });
  21268. };
  21269. /**
  21270. * Add a mesh as LOD level triggered at the given distance.
  21271. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21272. * @param {number} distance The distance from the center of the object to show this level
  21273. * @param {Mesh} mesh The mesh to be added as LOD level
  21274. * @return {Mesh} This mesh (for chaining)
  21275. */
  21276. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21277. if (mesh && mesh._masterMesh) {
  21278. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21279. return this;
  21280. }
  21281. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21282. this._LODLevels.push(level);
  21283. if (mesh) {
  21284. mesh._masterMesh = this;
  21285. }
  21286. this._sortLODLevels();
  21287. return this;
  21288. };
  21289. /**
  21290. * Returns the LOD level mesh at the passed distance or null if not found.
  21291. * It is related to the method `addLODLevel(distance, mesh)`.
  21292. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21293. * Returns an object Mesh or `null`.
  21294. */
  21295. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21296. for (var index = 0; index < this._LODLevels.length; index++) {
  21297. var level = this._LODLevels[index];
  21298. if (level.distance === distance) {
  21299. return level.mesh;
  21300. }
  21301. }
  21302. return null;
  21303. };
  21304. /**
  21305. * Remove a mesh from the LOD array
  21306. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21307. * @param {Mesh} mesh The mesh to be removed.
  21308. * @return {Mesh} This mesh (for chaining)
  21309. */
  21310. Mesh.prototype.removeLODLevel = function (mesh) {
  21311. for (var index = 0; index < this._LODLevels.length; index++) {
  21312. if (this._LODLevels[index].mesh === mesh) {
  21313. this._LODLevels.splice(index, 1);
  21314. if (mesh) {
  21315. mesh._masterMesh = null;
  21316. }
  21317. }
  21318. }
  21319. this._sortLODLevels();
  21320. return this;
  21321. };
  21322. /**
  21323. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21324. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21325. */
  21326. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21327. if (!this._LODLevels || this._LODLevels.length === 0) {
  21328. return this;
  21329. }
  21330. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21331. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21332. if (this.onLODLevelSelection) {
  21333. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21334. }
  21335. return this;
  21336. }
  21337. for (var index = 0; index < this._LODLevels.length; index++) {
  21338. var level = this._LODLevels[index];
  21339. if (level.distance < distanceToCamera) {
  21340. if (level.mesh) {
  21341. level.mesh._preActivate();
  21342. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21343. }
  21344. if (this.onLODLevelSelection) {
  21345. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21346. }
  21347. return level.mesh;
  21348. }
  21349. }
  21350. if (this.onLODLevelSelection) {
  21351. this.onLODLevelSelection(distanceToCamera, this, this);
  21352. }
  21353. return this;
  21354. };
  21355. Object.defineProperty(Mesh.prototype, "geometry", {
  21356. /**
  21357. * Returns the mesh internal Geometry object.
  21358. */
  21359. get: function () {
  21360. return this._geometry;
  21361. },
  21362. enumerable: true,
  21363. configurable: true
  21364. });
  21365. /**
  21366. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21367. */
  21368. Mesh.prototype.getTotalVertices = function () {
  21369. if (!this._geometry) {
  21370. return 0;
  21371. }
  21372. return this._geometry.getTotalVertices();
  21373. };
  21374. /**
  21375. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21376. * 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.
  21377. * You can force the copy with forceCopy === true
  21378. * Returns null if the mesh has no geometry or no vertex buffer.
  21379. * Possible `kind` values :
  21380. * - BABYLON.VertexBuffer.PositionKind
  21381. * - BABYLON.VertexBuffer.UVKind
  21382. * - BABYLON.VertexBuffer.UV2Kind
  21383. * - BABYLON.VertexBuffer.UV3Kind
  21384. * - BABYLON.VertexBuffer.UV4Kind
  21385. * - BABYLON.VertexBuffer.UV5Kind
  21386. * - BABYLON.VertexBuffer.UV6Kind
  21387. * - BABYLON.VertexBuffer.ColorKind
  21388. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21389. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21390. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21391. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21392. */
  21393. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21394. if (!this._geometry) {
  21395. return null;
  21396. }
  21397. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21398. };
  21399. /**
  21400. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21401. * Returns `undefined` if the mesh has no geometry.
  21402. * Possible `kind` values :
  21403. * - BABYLON.VertexBuffer.PositionKind
  21404. * - BABYLON.VertexBuffer.UVKind
  21405. * - BABYLON.VertexBuffer.UV2Kind
  21406. * - BABYLON.VertexBuffer.UV3Kind
  21407. * - BABYLON.VertexBuffer.UV4Kind
  21408. * - BABYLON.VertexBuffer.UV5Kind
  21409. * - BABYLON.VertexBuffer.UV6Kind
  21410. * - BABYLON.VertexBuffer.ColorKind
  21411. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21412. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21413. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21414. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21415. */
  21416. Mesh.prototype.getVertexBuffer = function (kind) {
  21417. if (!this._geometry) {
  21418. return undefined;
  21419. }
  21420. return this._geometry.getVertexBuffer(kind);
  21421. };
  21422. /**
  21423. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21424. * Possible `kind` values :
  21425. * - BABYLON.VertexBuffer.PositionKind
  21426. * - BABYLON.VertexBuffer.UVKind
  21427. * - BABYLON.VertexBuffer.UV2Kind
  21428. * - BABYLON.VertexBuffer.UV3Kind
  21429. * - BABYLON.VertexBuffer.UV4Kind
  21430. * - BABYLON.VertexBuffer.UV5Kind
  21431. * - BABYLON.VertexBuffer.UV6Kind
  21432. * - BABYLON.VertexBuffer.ColorKind
  21433. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21434. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21435. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21436. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21437. */
  21438. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21439. if (!this._geometry) {
  21440. if (this._delayInfo) {
  21441. return this._delayInfo.indexOf(kind) !== -1;
  21442. }
  21443. return false;
  21444. }
  21445. return this._geometry.isVerticesDataPresent(kind);
  21446. };
  21447. /**
  21448. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21449. * Possible `kind` values :
  21450. * - BABYLON.VertexBuffer.PositionKind
  21451. * - BABYLON.VertexBuffer.UVKind
  21452. * - BABYLON.VertexBuffer.UV2Kind
  21453. * - BABYLON.VertexBuffer.UV3Kind
  21454. * - BABYLON.VertexBuffer.UV4Kind
  21455. * - BABYLON.VertexBuffer.UV5Kind
  21456. * - BABYLON.VertexBuffer.UV6Kind
  21457. * - BABYLON.VertexBuffer.ColorKind
  21458. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21459. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21460. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21461. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21462. */
  21463. Mesh.prototype.getVerticesDataKinds = function () {
  21464. if (!this._geometry) {
  21465. var result = [];
  21466. if (this._delayInfo) {
  21467. this._delayInfo.forEach(function (kind, index, array) {
  21468. result.push(kind);
  21469. });
  21470. }
  21471. return result;
  21472. }
  21473. return this._geometry.getVerticesDataKinds();
  21474. };
  21475. /**
  21476. * Returns a positive integer : the total number of indices in this mesh geometry.
  21477. * Returns zero if the mesh has no geometry.
  21478. */
  21479. Mesh.prototype.getTotalIndices = function () {
  21480. if (!this._geometry) {
  21481. return 0;
  21482. }
  21483. return this._geometry.getTotalIndices();
  21484. };
  21485. /**
  21486. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21487. * 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.
  21488. * Returns an empty array if the mesh has no geometry.
  21489. */
  21490. Mesh.prototype.getIndices = function (copyWhenShared) {
  21491. if (!this._geometry) {
  21492. return [];
  21493. }
  21494. return this._geometry.getIndices(copyWhenShared);
  21495. };
  21496. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21497. get: function () {
  21498. return this._masterMesh !== null && this._masterMesh !== undefined;
  21499. },
  21500. enumerable: true,
  21501. configurable: true
  21502. });
  21503. /**
  21504. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21505. */
  21506. Mesh.prototype.isReady = function () {
  21507. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21508. return false;
  21509. }
  21510. return _super.prototype.isReady.call(this);
  21511. };
  21512. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  21513. get: function () {
  21514. return this._sideOrientation;
  21515. },
  21516. /**
  21517. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  21518. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  21519. */
  21520. set: function (sideO) {
  21521. this._sideOrientation = sideO;
  21522. },
  21523. enumerable: true,
  21524. configurable: true
  21525. });
  21526. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21527. /**
  21528. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21529. * This property is pertinent only for updatable parametric shapes.
  21530. */
  21531. get: function () {
  21532. return this._areNormalsFrozen;
  21533. },
  21534. enumerable: true,
  21535. configurable: true
  21536. });
  21537. /**
  21538. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21539. * It has no effect at all on other shapes.
  21540. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21541. * Returns the Mesh.
  21542. */
  21543. Mesh.prototype.freezeNormals = function () {
  21544. this._areNormalsFrozen = true;
  21545. return this;
  21546. };
  21547. /**
  21548. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21549. * It has no effect at all on other shapes.
  21550. * It reactivates the mesh normals computation if it was previously frozen.
  21551. * Returns the Mesh.
  21552. */
  21553. Mesh.prototype.unfreezeNormals = function () {
  21554. this._areNormalsFrozen = false;
  21555. return this;
  21556. };
  21557. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21558. /**
  21559. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21560. */
  21561. set: function (count) {
  21562. this._overridenInstanceCount = count;
  21563. },
  21564. enumerable: true,
  21565. configurable: true
  21566. });
  21567. // Methods
  21568. Mesh.prototype._preActivate = function () {
  21569. var sceneRenderId = this.getScene().getRenderId();
  21570. if (this._preActivateId === sceneRenderId) {
  21571. return this;
  21572. }
  21573. this._preActivateId = sceneRenderId;
  21574. this._visibleInstances = null;
  21575. return this;
  21576. };
  21577. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21578. if (this._visibleInstances) {
  21579. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21580. }
  21581. return this;
  21582. };
  21583. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21584. if (!this._visibleInstances) {
  21585. this._visibleInstances = {};
  21586. this._visibleInstances.defaultRenderId = renderId;
  21587. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21588. }
  21589. if (!this._visibleInstances[renderId]) {
  21590. this._visibleInstances[renderId] = new Array();
  21591. }
  21592. this._visibleInstances[renderId].push(instance);
  21593. return this;
  21594. };
  21595. /**
  21596. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21597. * This means the mesh underlying bounding box and sphere are recomputed.
  21598. * Returns the Mesh.
  21599. */
  21600. Mesh.prototype.refreshBoundingInfo = function () {
  21601. if (this._boundingInfo.isLocked) {
  21602. return;
  21603. }
  21604. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21605. if (data) {
  21606. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21607. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21608. }
  21609. if (this.subMeshes) {
  21610. for (var index = 0; index < this.subMeshes.length; index++) {
  21611. this.subMeshes[index].refreshBoundingInfo();
  21612. }
  21613. }
  21614. this._updateBoundingInfo();
  21615. return this;
  21616. };
  21617. Mesh.prototype._createGlobalSubMesh = function (force) {
  21618. var totalVertices = this.getTotalVertices();
  21619. if (!totalVertices || !this.getIndices()) {
  21620. return null;
  21621. }
  21622. // Check if we need to recreate the submeshes
  21623. if (this.subMeshes && this.subMeshes.length > 0) {
  21624. var totalIndices = this.getIndices().length;
  21625. var needToRecreate = false;
  21626. if (force) {
  21627. needToRecreate = true;
  21628. }
  21629. else {
  21630. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21631. var submesh = _a[_i];
  21632. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21633. needToRecreate = true;
  21634. break;
  21635. }
  21636. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21637. needToRecreate = true;
  21638. break;
  21639. }
  21640. }
  21641. }
  21642. if (!needToRecreate) {
  21643. return;
  21644. }
  21645. }
  21646. this.releaseSubMeshes();
  21647. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21648. };
  21649. Mesh.prototype.subdivide = function (count) {
  21650. if (count < 1) {
  21651. return;
  21652. }
  21653. var totalIndices = this.getTotalIndices();
  21654. var subdivisionSize = (totalIndices / count) | 0;
  21655. var offset = 0;
  21656. // Ensure that subdivisionSize is a multiple of 3
  21657. while (subdivisionSize % 3 !== 0) {
  21658. subdivisionSize++;
  21659. }
  21660. this.releaseSubMeshes();
  21661. for (var index = 0; index < count; index++) {
  21662. if (offset >= totalIndices) {
  21663. break;
  21664. }
  21665. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21666. offset += subdivisionSize;
  21667. }
  21668. this.synchronizeInstances();
  21669. };
  21670. /**
  21671. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21672. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21673. * The `data` are either a numeric array either a Float32Array.
  21674. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21675. * 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).
  21676. * Note that a new underlying VertexBuffer object is created each call.
  21677. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21678. *
  21679. * Possible `kind` values :
  21680. * - BABYLON.VertexBuffer.PositionKind
  21681. * - BABYLON.VertexBuffer.UVKind
  21682. * - BABYLON.VertexBuffer.UV2Kind
  21683. * - BABYLON.VertexBuffer.UV3Kind
  21684. * - BABYLON.VertexBuffer.UV4Kind
  21685. * - BABYLON.VertexBuffer.UV5Kind
  21686. * - BABYLON.VertexBuffer.UV6Kind
  21687. * - BABYLON.VertexBuffer.ColorKind
  21688. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21689. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21690. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21691. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21692. *
  21693. * Returns the Mesh.
  21694. */
  21695. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21696. if (!this._geometry) {
  21697. var vertexData = new BABYLON.VertexData();
  21698. vertexData.set(data, kind);
  21699. var scene = this.getScene();
  21700. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21701. }
  21702. else {
  21703. this._geometry.setVerticesData(kind, data, updatable, stride);
  21704. }
  21705. return this;
  21706. };
  21707. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21708. if (updatable === void 0) { updatable = true; }
  21709. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21710. return;
  21711. }
  21712. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21713. };
  21714. /**
  21715. * Sets the mesh VertexBuffer.
  21716. * Returns the Mesh.
  21717. */
  21718. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21719. if (!this._geometry) {
  21720. var scene = this.getScene();
  21721. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21722. }
  21723. this._geometry.setVerticesBuffer(buffer);
  21724. return this;
  21725. };
  21726. /**
  21727. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21728. * If the mesh has no geometry, it is simply returned as it is.
  21729. * The `data` are either a numeric array either a Float32Array.
  21730. * No new underlying VertexBuffer object is created.
  21731. * 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.
  21732. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21733. *
  21734. * Possible `kind` values :
  21735. * - BABYLON.VertexBuffer.PositionKind
  21736. * - BABYLON.VertexBuffer.UVKind
  21737. * - BABYLON.VertexBuffer.UV2Kind
  21738. * - BABYLON.VertexBuffer.UV3Kind
  21739. * - BABYLON.VertexBuffer.UV4Kind
  21740. * - BABYLON.VertexBuffer.UV5Kind
  21741. * - BABYLON.VertexBuffer.UV6Kind
  21742. * - BABYLON.VertexBuffer.ColorKind
  21743. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21744. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21745. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21746. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21747. *
  21748. * Returns the Mesh.
  21749. */
  21750. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21751. if (!this._geometry) {
  21752. return;
  21753. }
  21754. if (!makeItUnique) {
  21755. this._geometry.updateVerticesData(kind, data, updateExtends);
  21756. }
  21757. else {
  21758. this.makeGeometryUnique();
  21759. this.updateVerticesData(kind, data, updateExtends, false);
  21760. }
  21761. return this;
  21762. };
  21763. /**
  21764. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21765. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21766. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21767. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21768. * Returns the Mesh.
  21769. */
  21770. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21771. if (computeNormals === void 0) { computeNormals = true; }
  21772. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21773. positionFunction(positions);
  21774. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21775. if (computeNormals) {
  21776. var indices = this.getIndices();
  21777. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21778. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21779. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21780. }
  21781. return this;
  21782. };
  21783. /**
  21784. * Creates a un-shared specific occurence of the geometry for the mesh.
  21785. * Returns the Mesh.
  21786. */
  21787. Mesh.prototype.makeGeometryUnique = function () {
  21788. if (!this._geometry) {
  21789. return;
  21790. }
  21791. var oldGeometry = this._geometry;
  21792. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21793. oldGeometry.releaseForMesh(this, true);
  21794. geometry.applyToMesh(this);
  21795. return this;
  21796. };
  21797. /**
  21798. * Sets the mesh indices.
  21799. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21800. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21801. * This method creates a new index buffer each call.
  21802. * Returns the Mesh.
  21803. */
  21804. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21805. if (!this._geometry) {
  21806. var vertexData = new BABYLON.VertexData();
  21807. vertexData.indices = indices;
  21808. var scene = this.getScene();
  21809. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21810. }
  21811. else {
  21812. this._geometry.setIndices(indices, totalVertices);
  21813. }
  21814. return this;
  21815. };
  21816. /**
  21817. * Invert the geometry to move from a right handed system to a left handed one.
  21818. * Returns the Mesh.
  21819. */
  21820. Mesh.prototype.toLeftHanded = function () {
  21821. if (!this._geometry) {
  21822. return;
  21823. }
  21824. this._geometry.toLeftHanded();
  21825. return this;
  21826. };
  21827. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21828. var engine = this.getScene().getEngine();
  21829. // Wireframe
  21830. var indexToBind;
  21831. if (this._unIndexed) {
  21832. indexToBind = null;
  21833. }
  21834. else {
  21835. switch (fillMode) {
  21836. case BABYLON.Material.PointFillMode:
  21837. indexToBind = null;
  21838. break;
  21839. case BABYLON.Material.WireFrameFillMode:
  21840. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21841. break;
  21842. default:
  21843. case BABYLON.Material.TriangleFillMode:
  21844. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21845. break;
  21846. }
  21847. }
  21848. // VBOs
  21849. this._geometry._bind(effect, indexToBind);
  21850. return this;
  21851. };
  21852. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21853. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21854. return this;
  21855. }
  21856. this.onBeforeDrawObservable.notifyObservers(this);
  21857. var engine = this.getScene().getEngine();
  21858. // Draw order
  21859. switch (fillMode) {
  21860. case BABYLON.Material.PointFillMode:
  21861. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21862. break;
  21863. case BABYLON.Material.WireFrameFillMode:
  21864. if (this._unIndexed) {
  21865. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21866. }
  21867. else {
  21868. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  21869. }
  21870. break;
  21871. default:
  21872. if (this._unIndexed) {
  21873. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21874. }
  21875. else {
  21876. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21877. }
  21878. }
  21879. return this;
  21880. };
  21881. /**
  21882. * Registers for this mesh a javascript function called just before the rendering process.
  21883. * This function is passed the current mesh.
  21884. * Return the Mesh.
  21885. */
  21886. Mesh.prototype.registerBeforeRender = function (func) {
  21887. this.onBeforeRenderObservable.add(func);
  21888. return this;
  21889. };
  21890. /**
  21891. * Disposes a previously registered javascript function called before the rendering.
  21892. * This function is passed the current mesh.
  21893. * Returns the Mesh.
  21894. */
  21895. Mesh.prototype.unregisterBeforeRender = function (func) {
  21896. this.onBeforeRenderObservable.removeCallback(func);
  21897. return this;
  21898. };
  21899. /**
  21900. * Registers for this mesh a javascript function called just after the rendering is complete.
  21901. * This function is passed the current mesh.
  21902. * Returns the Mesh.
  21903. */
  21904. Mesh.prototype.registerAfterRender = function (func) {
  21905. this.onAfterRenderObservable.add(func);
  21906. return this;
  21907. };
  21908. /**
  21909. * Disposes a previously registered javascript function called after the rendering.
  21910. * This function is passed the current mesh.
  21911. * Return the Mesh.
  21912. */
  21913. Mesh.prototype.unregisterAfterRender = function (func) {
  21914. this.onAfterRenderObservable.removeCallback(func);
  21915. return this;
  21916. };
  21917. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21918. var scene = this.getScene();
  21919. this._batchCache.mustReturn = false;
  21920. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21921. this._batchCache.visibleInstances[subMeshId] = null;
  21922. if (this._visibleInstances) {
  21923. var currentRenderId = scene.getRenderId();
  21924. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21925. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21926. var selfRenderId = this._renderId;
  21927. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21928. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21929. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21930. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21931. }
  21932. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21933. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21934. this._batchCache.mustReturn = true;
  21935. return this._batchCache;
  21936. }
  21937. if (currentRenderId !== selfRenderId) {
  21938. this._batchCache.renderSelf[subMeshId] = false;
  21939. }
  21940. }
  21941. this._renderIdForInstances[subMeshId] = currentRenderId;
  21942. }
  21943. return this._batchCache;
  21944. };
  21945. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21946. var visibleInstances = batch.visibleInstances[subMesh._id];
  21947. var matricesCount = visibleInstances.length + 1;
  21948. var bufferSize = matricesCount * 16 * 4;
  21949. var currentInstancesBufferSize = this._instancesBufferSize;
  21950. var instancesBuffer = this._instancesBuffer;
  21951. while (this._instancesBufferSize < bufferSize) {
  21952. this._instancesBufferSize *= 2;
  21953. }
  21954. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21955. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21956. }
  21957. var offset = 0;
  21958. var instancesCount = 0;
  21959. var world = this.getWorldMatrix();
  21960. if (batch.renderSelf[subMesh._id]) {
  21961. world.copyToArray(this._instancesData, offset);
  21962. offset += 16;
  21963. instancesCount++;
  21964. }
  21965. if (visibleInstances) {
  21966. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21967. var instance = visibleInstances[instanceIndex];
  21968. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21969. offset += 16;
  21970. instancesCount++;
  21971. }
  21972. }
  21973. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21974. if (instancesBuffer) {
  21975. instancesBuffer.dispose();
  21976. }
  21977. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21978. this._instancesBuffer = instancesBuffer;
  21979. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21980. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21981. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21982. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21983. }
  21984. else {
  21985. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21986. }
  21987. this._bind(subMesh, effect, fillMode);
  21988. this._draw(subMesh, fillMode, instancesCount);
  21989. engine.unbindInstanceAttributes();
  21990. return this;
  21991. };
  21992. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21993. var scene = this.getScene();
  21994. var engine = scene.getEngine();
  21995. if (hardwareInstancedRendering) {
  21996. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21997. }
  21998. else {
  21999. if (batch.renderSelf[subMesh._id]) {
  22000. // Draw
  22001. if (onBeforeDraw) {
  22002. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  22003. }
  22004. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  22005. }
  22006. if (batch.visibleInstances[subMesh._id]) {
  22007. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22008. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22009. // World
  22010. var world = instance.getWorldMatrix();
  22011. if (onBeforeDraw) {
  22012. onBeforeDraw(true, world, effectiveMaterial);
  22013. }
  22014. // Draw
  22015. this._draw(subMesh, fillMode);
  22016. }
  22017. }
  22018. }
  22019. return this;
  22020. };
  22021. /**
  22022. * Triggers the draw call for the mesh.
  22023. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  22024. * Returns the Mesh.
  22025. */
  22026. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  22027. this.checkOcclusionQuery();
  22028. if (this._isOccluded) {
  22029. return;
  22030. }
  22031. var scene = this.getScene();
  22032. // Managing instances
  22033. var batch = this._getInstancesRenderList(subMesh._id);
  22034. if (batch.mustReturn) {
  22035. return this;
  22036. }
  22037. // Checking geometry state
  22038. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22039. return this;
  22040. }
  22041. var callbackIndex;
  22042. this.onBeforeRenderObservable.notifyObservers(this);
  22043. var engine = scene.getEngine();
  22044. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  22045. // Material
  22046. var effectiveMaterial = subMesh.getMaterial();
  22047. if (!effectiveMaterial) {
  22048. return this;
  22049. }
  22050. if (effectiveMaterial.storeEffectOnSubMeshes) {
  22051. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  22052. return this;
  22053. }
  22054. }
  22055. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  22056. return this;
  22057. }
  22058. // Alpha mode
  22059. if (enableAlphaMode) {
  22060. engine.setAlphaMode(effectiveMaterial.alphaMode);
  22061. }
  22062. // Outline - step 1
  22063. var savedDepthWrite = engine.getDepthWrite();
  22064. if (this.renderOutline) {
  22065. engine.setDepthWrite(false);
  22066. scene.getOutlineRenderer().render(subMesh, batch);
  22067. engine.setDepthWrite(savedDepthWrite);
  22068. }
  22069. var effect;
  22070. if (effectiveMaterial.storeEffectOnSubMeshes) {
  22071. effect = subMesh.effect;
  22072. }
  22073. else {
  22074. effect = effectiveMaterial.getEffect();
  22075. }
  22076. effectiveMaterial._preBind(effect);
  22077. // Bind
  22078. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  22079. if (!hardwareInstancedRendering) {
  22080. this._bind(subMesh, effect, fillMode);
  22081. }
  22082. var world = this.getWorldMatrix();
  22083. if (effectiveMaterial.storeEffectOnSubMeshes) {
  22084. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  22085. }
  22086. else {
  22087. effectiveMaterial.bind(world, this);
  22088. }
  22089. // Draw
  22090. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  22091. // Unbind
  22092. effectiveMaterial.unbind();
  22093. // Outline - step 2
  22094. if (this.renderOutline && savedDepthWrite) {
  22095. engine.setDepthWrite(true);
  22096. engine.setColorWrite(false);
  22097. scene.getOutlineRenderer().render(subMesh, batch);
  22098. engine.setColorWrite(true);
  22099. }
  22100. // Overlay
  22101. if (this.renderOverlay) {
  22102. var currentMode = engine.getAlphaMode();
  22103. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22104. scene.getOutlineRenderer().render(subMesh, batch, true);
  22105. engine.setAlphaMode(currentMode);
  22106. }
  22107. this.onAfterRenderObservable.notifyObservers(this);
  22108. return this;
  22109. };
  22110. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  22111. if (isInstance) {
  22112. effectiveMaterial.bindOnlyWorldMatrix(world);
  22113. }
  22114. return this;
  22115. };
  22116. /**
  22117. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  22118. */
  22119. Mesh.prototype.getEmittedParticleSystems = function () {
  22120. var results = new Array();
  22121. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22122. var particleSystem = this.getScene().particleSystems[index];
  22123. if (particleSystem.emitter === this) {
  22124. results.push(particleSystem);
  22125. }
  22126. }
  22127. return results;
  22128. };
  22129. /**
  22130. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  22131. */
  22132. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  22133. var results = new Array();
  22134. var descendants = this.getDescendants();
  22135. descendants.push(this);
  22136. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22137. var particleSystem = this.getScene().particleSystems[index];
  22138. var emitter = particleSystem.emitter;
  22139. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  22140. results.push(particleSystem);
  22141. }
  22142. }
  22143. return results;
  22144. };
  22145. Mesh.prototype._checkDelayState = function () {
  22146. var scene = this.getScene();
  22147. if (this._geometry) {
  22148. this._geometry.load(scene);
  22149. }
  22150. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22151. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22152. this._queueLoad(this, scene);
  22153. }
  22154. return this;
  22155. };
  22156. Mesh.prototype._queueLoad = function (mesh, scene) {
  22157. var _this = this;
  22158. scene._addPendingData(mesh);
  22159. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  22160. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22161. if (data instanceof ArrayBuffer) {
  22162. _this._delayLoadingFunction(data, _this);
  22163. }
  22164. else {
  22165. _this._delayLoadingFunction(JSON.parse(data), _this);
  22166. }
  22167. _this.instances.forEach(function (instance) {
  22168. instance._syncSubMeshes();
  22169. });
  22170. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22171. scene._removePendingData(_this);
  22172. }, function () { }, scene.database, getBinaryData);
  22173. return this;
  22174. };
  22175. /**
  22176. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  22177. */
  22178. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22179. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22180. return false;
  22181. }
  22182. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22183. return false;
  22184. }
  22185. this._checkDelayState();
  22186. return true;
  22187. };
  22188. /**
  22189. * Sets the mesh material by the material or multiMaterial `id` property.
  22190. * The material `id` is a string identifying the material or the multiMaterial.
  22191. * This method returns the Mesh.
  22192. */
  22193. Mesh.prototype.setMaterialByID = function (id) {
  22194. var materials = this.getScene().materials;
  22195. var index;
  22196. for (index = materials.length - 1; index > -1; index--) {
  22197. if (materials[index].id === id) {
  22198. this.material = materials[index];
  22199. return this;
  22200. }
  22201. }
  22202. // Multi
  22203. var multiMaterials = this.getScene().multiMaterials;
  22204. for (index = multiMaterials.length - 1; index > -1; index--) {
  22205. if (multiMaterials[index].id === id) {
  22206. this.material = multiMaterials[index];
  22207. return this;
  22208. }
  22209. }
  22210. return this;
  22211. };
  22212. /**
  22213. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22214. */
  22215. Mesh.prototype.getAnimatables = function () {
  22216. var results = [];
  22217. if (this.material) {
  22218. results.push(this.material);
  22219. }
  22220. if (this.skeleton) {
  22221. results.push(this.skeleton);
  22222. }
  22223. return results;
  22224. };
  22225. /**
  22226. * Modifies the mesh geometry according to the passed transformation matrix.
  22227. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22228. * The mesh normals are modified accordingly the same transformation.
  22229. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22230. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22231. * Returns the Mesh.
  22232. */
  22233. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22234. // Position
  22235. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22236. return this;
  22237. }
  22238. var submeshes = this.subMeshes.splice(0);
  22239. this._resetPointsArrayCache();
  22240. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22241. var temp = [];
  22242. var index;
  22243. for (index = 0; index < data.length; index += 3) {
  22244. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22245. }
  22246. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22247. // Normals
  22248. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22249. return this;
  22250. }
  22251. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22252. temp = [];
  22253. for (index = 0; index < data.length; index += 3) {
  22254. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22255. }
  22256. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22257. // flip faces?
  22258. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22259. this.flipFaces();
  22260. }
  22261. // Restore submeshes
  22262. this.releaseSubMeshes();
  22263. this.subMeshes = submeshes;
  22264. return this;
  22265. };
  22266. /**
  22267. * Modifies the mesh geometry according to its own current World Matrix.
  22268. * The mesh World Matrix is then reset.
  22269. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22270. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22271. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22272. * Returns the Mesh.
  22273. */
  22274. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22275. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22276. this.scaling.copyFromFloats(1, 1, 1);
  22277. this.position.copyFromFloats(0, 0, 0);
  22278. this.rotation.copyFromFloats(0, 0, 0);
  22279. //only if quaternion is already set
  22280. if (this.rotationQuaternion) {
  22281. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22282. }
  22283. this._worldMatrix = BABYLON.Matrix.Identity();
  22284. return this;
  22285. };
  22286. Object.defineProperty(Mesh.prototype, "_positions", {
  22287. // Cache
  22288. get: function () {
  22289. if (this._geometry) {
  22290. return this._geometry._positions;
  22291. }
  22292. return null;
  22293. },
  22294. enumerable: true,
  22295. configurable: true
  22296. });
  22297. Mesh.prototype._resetPointsArrayCache = function () {
  22298. if (this._geometry) {
  22299. this._geometry._resetPointsArrayCache();
  22300. }
  22301. return this;
  22302. };
  22303. Mesh.prototype._generatePointsArray = function () {
  22304. if (this._geometry) {
  22305. return this._geometry._generatePointsArray();
  22306. }
  22307. return false;
  22308. };
  22309. /**
  22310. * Returns a new Mesh object generated from the current mesh properties.
  22311. * This method must not get confused with createInstance().
  22312. * The parameter `name` is a string, the name given to the new mesh.
  22313. * The optional parameter `newParent` can be any Node object (default `null`).
  22314. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22315. * 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.
  22316. */
  22317. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22318. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22319. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22320. };
  22321. /**
  22322. * Disposes the mesh.
  22323. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22324. */
  22325. Mesh.prototype.dispose = function (doNotRecurse) {
  22326. var _this = this;
  22327. this.morphTargetManager = undefined;
  22328. if (this._geometry) {
  22329. this._geometry.releaseForMesh(this, true);
  22330. }
  22331. // Sources
  22332. var meshes = this.getScene().meshes;
  22333. meshes.forEach(function (mesh) {
  22334. if (mesh._source && mesh._source === _this) {
  22335. mesh._source = null;
  22336. }
  22337. });
  22338. this._source = null;
  22339. // Instances
  22340. if (this._instancesBuffer) {
  22341. this._instancesBuffer.dispose();
  22342. this._instancesBuffer = null;
  22343. }
  22344. while (this.instances.length) {
  22345. this.instances[0].dispose();
  22346. }
  22347. // Highlight layers.
  22348. var highlightLayers = this.getScene().highlightLayers;
  22349. for (var i = 0; i < highlightLayers.length; i++) {
  22350. var highlightLayer = highlightLayers[i];
  22351. if (highlightLayer) {
  22352. highlightLayer.removeMesh(this);
  22353. highlightLayer.removeExcludedMesh(this);
  22354. }
  22355. }
  22356. _super.prototype.dispose.call(this, doNotRecurse);
  22357. };
  22358. /**
  22359. * Modifies the mesh geometry according to a displacement map.
  22360. * 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.
  22361. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22362. * This method returns nothing.
  22363. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22364. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22365. * 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.
  22366. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22367. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22368. *
  22369. * Returns the Mesh.
  22370. */
  22371. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22372. var _this = this;
  22373. var scene = this.getScene();
  22374. var onload = function (img) {
  22375. // Getting height map data
  22376. var canvas = document.createElement("canvas");
  22377. var context = canvas.getContext("2d");
  22378. var heightMapWidth = img.width;
  22379. var heightMapHeight = img.height;
  22380. canvas.width = heightMapWidth;
  22381. canvas.height = heightMapHeight;
  22382. context.drawImage(img, 0, 0);
  22383. // Create VertexData from map data
  22384. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22385. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22386. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22387. //execute success callback, if set
  22388. if (onSuccess) {
  22389. onSuccess(_this);
  22390. }
  22391. };
  22392. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22393. return this;
  22394. };
  22395. /**
  22396. * Modifies the mesh geometry according to a displacementMap buffer.
  22397. * 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.
  22398. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22399. * This method returns nothing.
  22400. * 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.
  22401. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22402. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22403. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22404. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22405. *
  22406. * Returns the Mesh.
  22407. */
  22408. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22409. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22410. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22411. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22412. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22413. return this;
  22414. }
  22415. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22416. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22417. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22418. var position = BABYLON.Vector3.Zero();
  22419. var normal = BABYLON.Vector3.Zero();
  22420. var uv = BABYLON.Vector2.Zero();
  22421. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22422. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22423. for (var index = 0; index < positions.length; index += 3) {
  22424. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22425. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22426. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22427. // Compute height
  22428. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22429. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22430. var pos = (u + v * heightMapWidth) * 4;
  22431. var r = buffer[pos] / 255.0;
  22432. var g = buffer[pos + 1] / 255.0;
  22433. var b = buffer[pos + 2] / 255.0;
  22434. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22435. normal.normalize();
  22436. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22437. position = position.add(normal);
  22438. position.toArray(positions, index);
  22439. }
  22440. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22441. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22442. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22443. return this;
  22444. };
  22445. /**
  22446. * Modify the mesh to get a flat shading rendering.
  22447. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22448. * This method returns the Mesh.
  22449. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22450. */
  22451. Mesh.prototype.convertToFlatShadedMesh = function () {
  22452. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22453. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22454. var kinds = this.getVerticesDataKinds();
  22455. var vbs = [];
  22456. var data = [];
  22457. var newdata = [];
  22458. var updatableNormals = false;
  22459. var kindIndex;
  22460. var kind;
  22461. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22462. kind = kinds[kindIndex];
  22463. var vertexBuffer = this.getVertexBuffer(kind);
  22464. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22465. updatableNormals = vertexBuffer.isUpdatable();
  22466. kinds.splice(kindIndex, 1);
  22467. kindIndex--;
  22468. continue;
  22469. }
  22470. vbs[kind] = vertexBuffer;
  22471. data[kind] = vbs[kind].getData();
  22472. newdata[kind] = [];
  22473. }
  22474. // Save previous submeshes
  22475. var previousSubmeshes = this.subMeshes.slice(0);
  22476. var indices = this.getIndices();
  22477. var totalIndices = this.getTotalIndices();
  22478. // Generating unique vertices per face
  22479. var index;
  22480. for (index = 0; index < totalIndices; index++) {
  22481. var vertexIndex = indices[index];
  22482. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22483. kind = kinds[kindIndex];
  22484. var stride = vbs[kind].getStrideSize();
  22485. for (var offset = 0; offset < stride; offset++) {
  22486. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22487. }
  22488. }
  22489. }
  22490. // Updating faces & normal
  22491. var normals = [];
  22492. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22493. for (index = 0; index < totalIndices; index += 3) {
  22494. indices[index] = index;
  22495. indices[index + 1] = index + 1;
  22496. indices[index + 2] = index + 2;
  22497. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22498. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22499. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22500. var p1p2 = p1.subtract(p2);
  22501. var p3p2 = p3.subtract(p2);
  22502. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22503. // Store same normals for every vertex
  22504. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22505. normals.push(normal.x);
  22506. normals.push(normal.y);
  22507. normals.push(normal.z);
  22508. }
  22509. }
  22510. this.setIndices(indices);
  22511. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22512. // Updating vertex buffers
  22513. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22514. kind = kinds[kindIndex];
  22515. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22516. }
  22517. // Updating submeshes
  22518. this.releaseSubMeshes();
  22519. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22520. var previousOne = previousSubmeshes[submeshIndex];
  22521. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22522. }
  22523. this.synchronizeInstances();
  22524. return this;
  22525. };
  22526. /**
  22527. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22528. * In other words, more vertices, no more indices and a single bigger VBO.
  22529. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22530. * Returns the Mesh.
  22531. */
  22532. Mesh.prototype.convertToUnIndexedMesh = function () {
  22533. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22534. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22535. var kinds = this.getVerticesDataKinds();
  22536. var vbs = [];
  22537. var data = [];
  22538. var newdata = [];
  22539. var updatableNormals = false;
  22540. var kindIndex;
  22541. var kind;
  22542. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22543. kind = kinds[kindIndex];
  22544. var vertexBuffer = this.getVertexBuffer(kind);
  22545. vbs[kind] = vertexBuffer;
  22546. data[kind] = vbs[kind].getData();
  22547. newdata[kind] = [];
  22548. }
  22549. // Save previous submeshes
  22550. var previousSubmeshes = this.subMeshes.slice(0);
  22551. var indices = this.getIndices();
  22552. var totalIndices = this.getTotalIndices();
  22553. // Generating unique vertices per face
  22554. var index;
  22555. for (index = 0; index < totalIndices; index++) {
  22556. var vertexIndex = indices[index];
  22557. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22558. kind = kinds[kindIndex];
  22559. var stride = vbs[kind].getStrideSize();
  22560. for (var offset = 0; offset < stride; offset++) {
  22561. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22562. }
  22563. }
  22564. }
  22565. // Updating indices
  22566. for (index = 0; index < totalIndices; index += 3) {
  22567. indices[index] = index;
  22568. indices[index + 1] = index + 1;
  22569. indices[index + 2] = index + 2;
  22570. }
  22571. this.setIndices(indices);
  22572. // Updating vertex buffers
  22573. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22574. kind = kinds[kindIndex];
  22575. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22576. }
  22577. // Updating submeshes
  22578. this.releaseSubMeshes();
  22579. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22580. var previousOne = previousSubmeshes[submeshIndex];
  22581. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22582. }
  22583. this._unIndexed = true;
  22584. this.synchronizeInstances();
  22585. return this;
  22586. };
  22587. /**
  22588. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22589. * This method returns the Mesh.
  22590. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22591. */
  22592. Mesh.prototype.flipFaces = function (flipNormals) {
  22593. if (flipNormals === void 0) { flipNormals = false; }
  22594. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22595. var i;
  22596. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22597. for (i = 0; i < vertex_data.normals.length; i++) {
  22598. vertex_data.normals[i] *= -1;
  22599. }
  22600. }
  22601. var temp;
  22602. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22603. // reassign indices
  22604. temp = vertex_data.indices[i + 1];
  22605. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22606. vertex_data.indices[i + 2] = temp;
  22607. }
  22608. vertex_data.applyToMesh(this);
  22609. return this;
  22610. };
  22611. // Instances
  22612. /**
  22613. * Creates a new InstancedMesh object from the mesh model.
  22614. * An instance shares the same properties and the same material than its model.
  22615. * Only these properties of each instance can then be set individually :
  22616. * - position
  22617. * - rotation
  22618. * - rotationQuaternion
  22619. * - setPivotMatrix
  22620. * - scaling
  22621. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22622. * Warning : this method is not supported for Line mesh and LineSystem
  22623. */
  22624. Mesh.prototype.createInstance = function (name) {
  22625. return new BABYLON.InstancedMesh(name, this);
  22626. };
  22627. /**
  22628. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22629. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22630. * This method returns the Mesh.
  22631. */
  22632. Mesh.prototype.synchronizeInstances = function () {
  22633. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22634. var instance = this.instances[instanceIndex];
  22635. instance._syncSubMeshes();
  22636. }
  22637. return this;
  22638. };
  22639. /**
  22640. * Simplify the mesh according to the given array of settings.
  22641. * Function will return immediately and will simplify async. It returns the Mesh.
  22642. * @param settings a collection of simplification settings.
  22643. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22644. * @param type the type of simplification to run.
  22645. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22646. */
  22647. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22648. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22649. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22650. this.getScene().simplificationQueue.addTask({
  22651. settings: settings,
  22652. parallelProcessing: parallelProcessing,
  22653. mesh: this,
  22654. simplificationType: simplificationType,
  22655. successCallback: successCallback
  22656. });
  22657. return this;
  22658. };
  22659. /**
  22660. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22661. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22662. * This should be used together with the simplification to avoid disappearing triangles.
  22663. * Returns the Mesh.
  22664. * @param successCallback an optional success callback to be called after the optimization finished.
  22665. */
  22666. Mesh.prototype.optimizeIndices = function (successCallback) {
  22667. var _this = this;
  22668. var indices = this.getIndices();
  22669. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22670. var vectorPositions = [];
  22671. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22672. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22673. }
  22674. var dupes = [];
  22675. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22676. var realPos = vectorPositions.length - 1 - iteration;
  22677. var testedPosition = vectorPositions[realPos];
  22678. for (var j = 0; j < realPos; ++j) {
  22679. var againstPosition = vectorPositions[j];
  22680. if (testedPosition.equals(againstPosition)) {
  22681. dupes[realPos] = j;
  22682. break;
  22683. }
  22684. }
  22685. }, function () {
  22686. for (var i = 0; i < indices.length; ++i) {
  22687. indices[i] = dupes[indices[i]] || indices[i];
  22688. }
  22689. //indices are now reordered
  22690. var originalSubMeshes = _this.subMeshes.slice(0);
  22691. _this.setIndices(indices);
  22692. _this.subMeshes = originalSubMeshes;
  22693. if (successCallback) {
  22694. successCallback(_this);
  22695. }
  22696. });
  22697. return this;
  22698. };
  22699. Mesh.prototype.serialize = function (serializationObject) {
  22700. serializationObject.name = this.name;
  22701. serializationObject.id = this.id;
  22702. serializationObject.type = this.getClassName();
  22703. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22704. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22705. }
  22706. serializationObject.position = this.position.asArray();
  22707. if (this.rotationQuaternion) {
  22708. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22709. }
  22710. else if (this.rotation) {
  22711. serializationObject.rotation = this.rotation.asArray();
  22712. }
  22713. serializationObject.scaling = this.scaling.asArray();
  22714. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22715. serializationObject.isEnabled = this.isEnabled();
  22716. serializationObject.isVisible = this.isVisible;
  22717. serializationObject.infiniteDistance = this.infiniteDistance;
  22718. serializationObject.pickable = this.isPickable;
  22719. serializationObject.receiveShadows = this.receiveShadows;
  22720. serializationObject.billboardMode = this.billboardMode;
  22721. serializationObject.visibility = this.visibility;
  22722. serializationObject.checkCollisions = this.checkCollisions;
  22723. serializationObject.isBlocker = this.isBlocker;
  22724. // Parent
  22725. if (this.parent) {
  22726. serializationObject.parentId = this.parent.id;
  22727. }
  22728. // Geometry
  22729. var geometry = this._geometry;
  22730. if (geometry) {
  22731. var geometryId = geometry.id;
  22732. serializationObject.geometryId = geometryId;
  22733. // SubMeshes
  22734. serializationObject.subMeshes = [];
  22735. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22736. var subMesh = this.subMeshes[subIndex];
  22737. serializationObject.subMeshes.push({
  22738. materialIndex: subMesh.materialIndex,
  22739. verticesStart: subMesh.verticesStart,
  22740. verticesCount: subMesh.verticesCount,
  22741. indexStart: subMesh.indexStart,
  22742. indexCount: subMesh.indexCount
  22743. });
  22744. }
  22745. }
  22746. // Material
  22747. if (this.material) {
  22748. serializationObject.materialId = this.material.id;
  22749. }
  22750. else {
  22751. this.material = null;
  22752. }
  22753. // Morph targets
  22754. if (this.morphTargetManager) {
  22755. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22756. }
  22757. // Skeleton
  22758. if (this.skeleton) {
  22759. serializationObject.skeletonId = this.skeleton.id;
  22760. }
  22761. // Physics
  22762. //TODO implement correct serialization for physics impostors.
  22763. if (this.getPhysicsImpostor()) {
  22764. var impostor = this.getPhysicsImpostor();
  22765. serializationObject.physicsMass = impostor.getParam("mass");
  22766. serializationObject.physicsFriction = impostor.getParam("friction");
  22767. serializationObject.physicsRestitution = impostor.getParam("mass");
  22768. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  22769. }
  22770. // Metadata
  22771. if (this.metadata) {
  22772. serializationObject.metadata = this.metadata;
  22773. }
  22774. // Instances
  22775. serializationObject.instances = [];
  22776. for (var index = 0; index < this.instances.length; index++) {
  22777. var instance = this.instances[index];
  22778. var serializationInstance = {
  22779. name: instance.name,
  22780. position: instance.position.asArray(),
  22781. scaling: instance.scaling.asArray()
  22782. };
  22783. if (instance.rotationQuaternion) {
  22784. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  22785. }
  22786. else if (instance.rotation) {
  22787. serializationInstance.rotation = instance.rotation.asArray();
  22788. }
  22789. serializationObject.instances.push(serializationInstance);
  22790. // Animations
  22791. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  22792. serializationInstance.ranges = instance.serializeAnimationRanges();
  22793. }
  22794. //
  22795. // Animations
  22796. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22797. serializationObject.ranges = this.serializeAnimationRanges();
  22798. // Layer mask
  22799. serializationObject.layerMask = this.layerMask;
  22800. // Alpha
  22801. serializationObject.alphaIndex = this.alphaIndex;
  22802. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  22803. // Overlay
  22804. serializationObject.overlayAlpha = this.overlayAlpha;
  22805. serializationObject.overlayColor = this.overlayColor.asArray();
  22806. serializationObject.renderOverlay = this.renderOverlay;
  22807. // Fog
  22808. serializationObject.applyFog = this.applyFog;
  22809. // Action Manager
  22810. if (this.actionManager) {
  22811. serializationObject.actions = this.actionManager.serialize(this.name);
  22812. }
  22813. };
  22814. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  22815. if (!this.geometry) {
  22816. return;
  22817. }
  22818. this._markSubMeshesAsAttributesDirty();
  22819. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  22820. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  22821. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  22822. this.morphTargetManager = undefined;
  22823. return;
  22824. }
  22825. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  22826. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  22827. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  22828. if (morphTarget.hasNormals) {
  22829. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  22830. }
  22831. if (morphTarget.hasTangents) {
  22832. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  22833. }
  22834. }
  22835. }
  22836. else {
  22837. var index = 0;
  22838. // Positions
  22839. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  22840. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  22841. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  22842. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  22843. }
  22844. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  22845. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  22846. }
  22847. index++;
  22848. }
  22849. }
  22850. };
  22851. // Statics
  22852. /**
  22853. * Returns a new Mesh object what is a deep copy of the passed mesh.
  22854. * The parameter `parsedMesh` is the mesh to be copied.
  22855. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  22856. */
  22857. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  22858. var mesh;
  22859. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  22860. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  22861. }
  22862. else {
  22863. mesh = new Mesh(parsedMesh.name, scene);
  22864. }
  22865. mesh.id = parsedMesh.id;
  22866. if (BABYLON.Tags) {
  22867. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  22868. }
  22869. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  22870. if (parsedMesh.metadata !== undefined) {
  22871. mesh.metadata = parsedMesh.metadata;
  22872. }
  22873. if (parsedMesh.rotationQuaternion) {
  22874. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  22875. }
  22876. else if (parsedMesh.rotation) {
  22877. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  22878. }
  22879. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  22880. if (parsedMesh.localMatrix) {
  22881. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  22882. }
  22883. else if (parsedMesh.pivotMatrix) {
  22884. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  22885. }
  22886. mesh.setEnabled(parsedMesh.isEnabled);
  22887. mesh.isVisible = parsedMesh.isVisible;
  22888. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  22889. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  22890. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  22891. if (parsedMesh.applyFog !== undefined) {
  22892. mesh.applyFog = parsedMesh.applyFog;
  22893. }
  22894. if (parsedMesh.pickable !== undefined) {
  22895. mesh.isPickable = parsedMesh.pickable;
  22896. }
  22897. if (parsedMesh.alphaIndex !== undefined) {
  22898. mesh.alphaIndex = parsedMesh.alphaIndex;
  22899. }
  22900. mesh.receiveShadows = parsedMesh.receiveShadows;
  22901. mesh.billboardMode = parsedMesh.billboardMode;
  22902. if (parsedMesh.visibility !== undefined) {
  22903. mesh.visibility = parsedMesh.visibility;
  22904. }
  22905. mesh.checkCollisions = parsedMesh.checkCollisions;
  22906. if (parsedMesh.isBlocker !== undefined) {
  22907. mesh.isBlocker = parsedMesh.isBlocker;
  22908. }
  22909. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  22910. // freezeWorldMatrix
  22911. if (parsedMesh.freezeWorldMatrix) {
  22912. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  22913. }
  22914. // Parent
  22915. if (parsedMesh.parentId) {
  22916. mesh._waitingParentId = parsedMesh.parentId;
  22917. }
  22918. // Actions
  22919. if (parsedMesh.actions !== undefined) {
  22920. mesh._waitingActions = parsedMesh.actions;
  22921. }
  22922. // Overlay
  22923. if (parsedMesh.overlayAlpha !== undefined) {
  22924. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  22925. }
  22926. if (parsedMesh.overlayColor !== undefined) {
  22927. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  22928. }
  22929. if (parsedMesh.renderOverlay !== undefined) {
  22930. mesh.renderOverlay = parsedMesh.renderOverlay;
  22931. }
  22932. // Geometry
  22933. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  22934. if (parsedMesh.delayLoadingFile) {
  22935. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22936. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  22937. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  22938. if (parsedMesh._binaryInfo) {
  22939. mesh._binaryInfo = parsedMesh._binaryInfo;
  22940. }
  22941. mesh._delayInfo = [];
  22942. if (parsedMesh.hasUVs) {
  22943. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  22944. }
  22945. if (parsedMesh.hasUVs2) {
  22946. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  22947. }
  22948. if (parsedMesh.hasUVs3) {
  22949. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  22950. }
  22951. if (parsedMesh.hasUVs4) {
  22952. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  22953. }
  22954. if (parsedMesh.hasUVs5) {
  22955. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  22956. }
  22957. if (parsedMesh.hasUVs6) {
  22958. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  22959. }
  22960. if (parsedMesh.hasColors) {
  22961. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  22962. }
  22963. if (parsedMesh.hasMatricesIndices) {
  22964. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22965. }
  22966. if (parsedMesh.hasMatricesWeights) {
  22967. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22968. }
  22969. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  22970. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  22971. mesh._checkDelayState();
  22972. }
  22973. }
  22974. else {
  22975. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  22976. }
  22977. // Material
  22978. if (parsedMesh.materialId) {
  22979. mesh.setMaterialByID(parsedMesh.materialId);
  22980. }
  22981. else {
  22982. mesh.material = null;
  22983. }
  22984. // Morph targets
  22985. if (parsedMesh.morphTargetManagerId > -1) {
  22986. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  22987. }
  22988. // Skeleton
  22989. if (parsedMesh.skeletonId > -1) {
  22990. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  22991. if (parsedMesh.numBoneInfluencers) {
  22992. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  22993. }
  22994. }
  22995. // Animations
  22996. if (parsedMesh.animations) {
  22997. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22998. var parsedAnimation = parsedMesh.animations[animationIndex];
  22999. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23000. }
  23001. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  23002. }
  23003. if (parsedMesh.autoAnimate) {
  23004. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  23005. }
  23006. // Layer Mask
  23007. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  23008. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  23009. }
  23010. else {
  23011. mesh.layerMask = 0x0FFFFFFF;
  23012. }
  23013. // Physics
  23014. if (parsedMesh.physicsImpostor) {
  23015. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  23016. mass: parsedMesh.physicsMass,
  23017. friction: parsedMesh.physicsFriction,
  23018. restitution: parsedMesh.physicsRestitution
  23019. }, scene);
  23020. }
  23021. // Instances
  23022. if (parsedMesh.instances) {
  23023. for (var index = 0; index < parsedMesh.instances.length; index++) {
  23024. var parsedInstance = parsedMesh.instances[index];
  23025. var instance = mesh.createInstance(parsedInstance.name);
  23026. if (BABYLON.Tags) {
  23027. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  23028. }
  23029. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  23030. if (parsedInstance.parentId) {
  23031. instance._waitingParentId = parsedInstance.parentId;
  23032. }
  23033. if (parsedInstance.rotationQuaternion) {
  23034. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  23035. }
  23036. else if (parsedInstance.rotation) {
  23037. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  23038. }
  23039. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  23040. instance.checkCollisions = mesh.checkCollisions;
  23041. if (parsedMesh.animations) {
  23042. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23043. parsedAnimation = parsedMesh.animations[animationIndex];
  23044. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23045. }
  23046. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  23047. }
  23048. }
  23049. }
  23050. return mesh;
  23051. };
  23052. /**
  23053. * Creates a ribbon mesh.
  23054. * Please consider using the same method from the MeshBuilder class instead.
  23055. * 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.
  23056. *
  23057. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23058. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23059. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23060. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23061. * 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.
  23062. * 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.
  23063. * 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
  23064. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23065. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23066. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23067. */
  23068. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  23069. return BABYLON.MeshBuilder.CreateRibbon(name, {
  23070. pathArray: pathArray,
  23071. closeArray: closeArray,
  23072. closePath: closePath,
  23073. offset: offset,
  23074. updatable: updatable,
  23075. sideOrientation: sideOrientation,
  23076. instance: instance
  23077. }, scene);
  23078. };
  23079. /**
  23080. * Creates a plane polygonal mesh. By default, this is a disc.
  23081. * Please consider using the same method from the MeshBuilder class instead.
  23082. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23083. * 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.
  23084. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23085. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23086. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23087. */
  23088. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  23089. var options = {
  23090. radius: radius,
  23091. tessellation: tessellation,
  23092. sideOrientation: sideOrientation,
  23093. updatable: updatable
  23094. };
  23095. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  23096. };
  23097. /**
  23098. * Creates a box mesh.
  23099. * Please consider using the same method from the MeshBuilder class instead.
  23100. * The parameter `size` sets the size (float) of each box side (default 1).
  23101. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23102. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23103. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23104. */
  23105. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  23106. var options = {
  23107. size: size,
  23108. sideOrientation: sideOrientation,
  23109. updatable: updatable
  23110. };
  23111. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  23112. };
  23113. /**
  23114. * Creates a sphere mesh.
  23115. * Please consider using the same method from the MeshBuilder class instead.
  23116. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  23117. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  23118. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23119. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23120. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23121. */
  23122. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  23123. var options = {
  23124. segments: segments,
  23125. diameterX: diameter,
  23126. diameterY: diameter,
  23127. diameterZ: diameter,
  23128. sideOrientation: sideOrientation,
  23129. updatable: updatable
  23130. };
  23131. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  23132. };
  23133. /**
  23134. * Creates a cylinder or a cone mesh.
  23135. * Please consider using the same method from the MeshBuilder class instead.
  23136. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23137. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23138. * 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.
  23139. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23140. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23141. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23142. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23143. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23144. */
  23145. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  23146. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  23147. if (scene !== undefined) {
  23148. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  23149. updatable = scene;
  23150. }
  23151. scene = subdivisions;
  23152. subdivisions = 1;
  23153. }
  23154. var options = {
  23155. height: height,
  23156. diameterTop: diameterTop,
  23157. diameterBottom: diameterBottom,
  23158. tessellation: tessellation,
  23159. subdivisions: subdivisions,
  23160. sideOrientation: sideOrientation,
  23161. updatable: updatable
  23162. };
  23163. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  23164. };
  23165. // Torus (Code from SharpDX.org)
  23166. /**
  23167. * Creates a torus mesh.
  23168. * Please consider using the same method from the MeshBuilder class instead.
  23169. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23170. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23171. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23172. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23173. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23175. */
  23176. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  23177. var options = {
  23178. diameter: diameter,
  23179. thickness: thickness,
  23180. tessellation: tessellation,
  23181. sideOrientation: sideOrientation,
  23182. updatable: updatable
  23183. };
  23184. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23185. };
  23186. /**
  23187. * Creates a torus knot mesh.
  23188. * Please consider using the same method from the MeshBuilder class instead.
  23189. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23190. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23191. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23192. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23193. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23194. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23195. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23196. */
  23197. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23198. var options = {
  23199. radius: radius,
  23200. tube: tube,
  23201. radialSegments: radialSegments,
  23202. tubularSegments: tubularSegments,
  23203. p: p,
  23204. q: q,
  23205. sideOrientation: sideOrientation,
  23206. updatable: updatable
  23207. };
  23208. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23209. };
  23210. /**
  23211. * Creates a line mesh.
  23212. * Please consider using the same method from the MeshBuilder class instead.
  23213. * 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.
  23214. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23215. * The parameter `points` is an array successive Vector3.
  23216. * 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
  23217. * When updating an instance, remember that only point positions can change, not the number of points.
  23218. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23219. */
  23220. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23221. var options = {
  23222. points: points,
  23223. updatable: updatable,
  23224. instance: instance
  23225. };
  23226. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23227. };
  23228. /**
  23229. * Creates a dashed line mesh.
  23230. * Please consider using the same method from the MeshBuilder class instead.
  23231. * 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.
  23232. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23233. * The parameter `points` is an array successive Vector3.
  23234. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23235. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23236. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23237. * 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
  23238. * When updating an instance, remember that only point positions can change, not the number of points.
  23239. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23240. */
  23241. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23242. var options = {
  23243. points: points,
  23244. dashSize: dashSize,
  23245. gapSize: gapSize,
  23246. dashNb: dashNb,
  23247. updatable: updatable,
  23248. instance: instance
  23249. };
  23250. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23251. };
  23252. /**
  23253. * Creates a polygon mesh.
  23254. * Please consider using the same method from the MeshBuilder class instead.
  23255. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23256. * 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.
  23257. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23258. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23259. * Remember you can only change the shape positions, not their number when updating a polygon.
  23260. */
  23261. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23262. var options = {
  23263. shape: shape,
  23264. holes: holes,
  23265. updatable: updatable,
  23266. sideOrientation: sideOrientation
  23267. };
  23268. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23269. };
  23270. /**
  23271. * Creates an extruded polygon mesh, with depth in the Y direction.
  23272. * Please consider using the same method from the MeshBuilder class instead.
  23273. */
  23274. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23275. var options = {
  23276. shape: shape,
  23277. holes: holes,
  23278. depth: depth,
  23279. updatable: updatable,
  23280. sideOrientation: sideOrientation
  23281. };
  23282. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23283. };
  23284. /**
  23285. * Creates an extruded shape mesh.
  23286. * 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.
  23287. * Please consider using the same method from the MeshBuilder class instead.
  23288. *
  23289. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23290. * 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
  23291. * extruded along the Z axis.
  23292. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23293. * 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.
  23294. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23295. * 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
  23296. * 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
  23297. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23298. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23299. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23300. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23301. */
  23302. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23303. var options = {
  23304. shape: shape,
  23305. path: path,
  23306. scale: scale,
  23307. rotation: rotation,
  23308. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23309. sideOrientation: sideOrientation,
  23310. instance: instance,
  23311. updatable: updatable
  23312. };
  23313. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23314. };
  23315. /**
  23316. * Creates an custom extruded shape mesh.
  23317. * 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.
  23318. * Please consider using the same method from the MeshBuilder class instead.
  23319. *
  23320. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23321. * 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
  23322. * extruded along the Z axis.
  23323. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23324. * 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
  23325. * and the distance of this point from the begining of the path :
  23326. * ```javascript
  23327. * var rotationFunction = function(i, distance) {
  23328. * // do things
  23329. * return rotationValue; }
  23330. * ```
  23331. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23332. * 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
  23333. * and the distance of this point from the begining of the path :
  23334. * ```javascript
  23335. * var scaleFunction = function(i, distance) {
  23336. * // do things
  23337. * return scaleValue;}
  23338. * ```
  23339. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23340. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23341. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23342. * 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
  23343. * 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
  23344. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23345. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23346. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23347. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23348. */
  23349. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23350. var options = {
  23351. shape: shape,
  23352. path: path,
  23353. scaleFunction: scaleFunction,
  23354. rotationFunction: rotationFunction,
  23355. ribbonCloseArray: ribbonCloseArray,
  23356. ribbonClosePath: ribbonClosePath,
  23357. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23358. sideOrientation: sideOrientation,
  23359. instance: instance,
  23360. updatable: updatable
  23361. };
  23362. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23363. };
  23364. /**
  23365. * Creates lathe mesh.
  23366. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23367. * Please consider using the same method from the MeshBuilder class instead.
  23368. * 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
  23369. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23370. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23371. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23372. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23373. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23374. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23375. */
  23376. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23377. var options = {
  23378. shape: shape,
  23379. radius: radius,
  23380. tessellation: tessellation,
  23381. sideOrientation: sideOrientation,
  23382. updatable: updatable
  23383. };
  23384. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23385. };
  23386. /**
  23387. * Creates a plane mesh.
  23388. * Please consider using the same method from the MeshBuilder class instead.
  23389. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23390. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23391. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23392. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23393. */
  23394. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23395. var options = {
  23396. size: size,
  23397. width: size,
  23398. height: size,
  23399. sideOrientation: sideOrientation,
  23400. updatable: updatable
  23401. };
  23402. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23403. };
  23404. /**
  23405. * Creates a ground mesh.
  23406. * Please consider using the same method from the MeshBuilder class instead.
  23407. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23408. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23409. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23410. */
  23411. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23412. var options = {
  23413. width: width,
  23414. height: height,
  23415. subdivisions: subdivisions,
  23416. updatable: updatable
  23417. };
  23418. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23419. };
  23420. /**
  23421. * Creates a tiled ground mesh.
  23422. * Please consider using the same method from the MeshBuilder class instead.
  23423. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23424. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23425. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23426. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23427. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23428. * numbers of subdivisions on the ground width and height of each tile.
  23429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23430. */
  23431. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23432. var options = {
  23433. xmin: xmin,
  23434. zmin: zmin,
  23435. xmax: xmax,
  23436. zmax: zmax,
  23437. subdivisions: subdivisions,
  23438. precision: precision,
  23439. updatable: updatable
  23440. };
  23441. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23442. };
  23443. /**
  23444. * Creates a ground mesh from a height map.
  23445. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23446. * Please consider using the same method from the MeshBuilder class instead.
  23447. * The parameter `url` sets the URL of the height map image resource.
  23448. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23449. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23450. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23451. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23452. * 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).
  23453. * This function is passed the newly built mesh :
  23454. * ```javascript
  23455. * function(mesh) { // do things
  23456. * return; }
  23457. * ```
  23458. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23459. */
  23460. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23461. var options = {
  23462. width: width,
  23463. height: height,
  23464. subdivisions: subdivisions,
  23465. minHeight: minHeight,
  23466. maxHeight: maxHeight,
  23467. updatable: updatable,
  23468. onReady: onReady
  23469. };
  23470. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23471. };
  23472. /**
  23473. * Creates a tube mesh.
  23474. * 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.
  23475. * Please consider using the same method from the MeshBuilder class instead.
  23476. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23477. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23478. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23479. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23480. * 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.
  23481. * It must return a radius value (positive float) :
  23482. * ```javascript
  23483. * var radiusFunction = function(i, distance) {
  23484. * // do things
  23485. * return radius; }
  23486. * ```
  23487. * 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
  23488. * 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
  23489. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23490. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23491. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23492. */
  23493. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23494. var options = {
  23495. path: path,
  23496. radius: radius,
  23497. tessellation: tessellation,
  23498. radiusFunction: radiusFunction,
  23499. arc: 1,
  23500. cap: cap,
  23501. updatable: updatable,
  23502. sideOrientation: sideOrientation,
  23503. instance: instance
  23504. };
  23505. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23506. };
  23507. /**
  23508. * Creates a polyhedron mesh.
  23509. * Please consider using the same method from the MeshBuilder class instead.
  23510. * 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
  23511. * to choose the wanted type.
  23512. * The parameter `size` (positive float, default 1) sets the polygon size.
  23513. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23514. * 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`.
  23515. * 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
  23516. * 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)`).
  23517. * 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
  23518. * 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.
  23519. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23520. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23521. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23522. */
  23523. Mesh.CreatePolyhedron = function (name, options, scene) {
  23524. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23525. };
  23526. /**
  23527. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23528. * Please consider using the same method from the MeshBuilder class instead.
  23529. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23530. * 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`).
  23531. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23532. * 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.
  23533. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23534. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23535. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23536. */
  23537. Mesh.CreateIcoSphere = function (name, options, scene) {
  23538. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23539. };
  23540. /**
  23541. * Creates a decal mesh.
  23542. * Please consider using the same method from the MeshBuilder class instead.
  23543. * 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.
  23544. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23545. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23546. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23547. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23548. */
  23549. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23550. var options = {
  23551. position: position,
  23552. normal: normal,
  23553. size: size,
  23554. angle: angle
  23555. };
  23556. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23557. };
  23558. // Skeletons
  23559. /**
  23560. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23561. */
  23562. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23563. var source;
  23564. if (!this._sourcePositions) {
  23565. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23566. this._sourcePositions = new Float32Array(source);
  23567. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23568. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23569. }
  23570. }
  23571. return this._sourcePositions;
  23572. };
  23573. /**
  23574. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23575. */
  23576. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23577. var source;
  23578. if (!this._sourceNormals) {
  23579. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23580. this._sourceNormals = new Float32Array(source);
  23581. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23582. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23583. }
  23584. }
  23585. return this._sourceNormals;
  23586. };
  23587. /**
  23588. * Updates the vertex buffer by applying transformation from the bones.
  23589. * Returns the Mesh.
  23590. *
  23591. * @param {skeleton} skeleton to apply
  23592. */
  23593. Mesh.prototype.applySkeleton = function (skeleton) {
  23594. if (!this.geometry) {
  23595. return this;
  23596. }
  23597. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23598. return this;
  23599. }
  23600. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23601. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23602. return this;
  23603. }
  23604. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23605. return this;
  23606. }
  23607. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23608. return this;
  23609. }
  23610. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23611. return this;
  23612. }
  23613. if (!this._sourcePositions) {
  23614. var submeshes = this.subMeshes.slice();
  23615. this.setPositionsForCPUSkinning();
  23616. this.subMeshes = submeshes;
  23617. }
  23618. if (!this._sourceNormals) {
  23619. this.setNormalsForCPUSkinning();
  23620. }
  23621. // positionsData checks for not being Float32Array will only pass at most once
  23622. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23623. if (!(positionsData instanceof Float32Array)) {
  23624. positionsData = new Float32Array(positionsData);
  23625. }
  23626. // normalsData checks for not being Float32Array will only pass at most once
  23627. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23628. if (!(normalsData instanceof Float32Array)) {
  23629. normalsData = new Float32Array(normalsData);
  23630. }
  23631. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23632. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23633. var needExtras = this.numBoneInfluencers > 4;
  23634. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23635. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23636. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23637. var tempVector3 = BABYLON.Vector3.Zero();
  23638. var finalMatrix = new BABYLON.Matrix();
  23639. var tempMatrix = new BABYLON.Matrix();
  23640. var matWeightIdx = 0;
  23641. var inf;
  23642. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23643. var weight;
  23644. for (inf = 0; inf < 4; inf++) {
  23645. weight = matricesWeightsData[matWeightIdx + inf];
  23646. if (weight > 0) {
  23647. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23648. finalMatrix.addToSelf(tempMatrix);
  23649. }
  23650. else
  23651. break;
  23652. }
  23653. if (needExtras) {
  23654. for (inf = 0; inf < 4; inf++) {
  23655. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23656. if (weight > 0) {
  23657. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23658. finalMatrix.addToSelf(tempMatrix);
  23659. }
  23660. else
  23661. break;
  23662. }
  23663. }
  23664. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23665. tempVector3.toArray(positionsData, index);
  23666. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23667. tempVector3.toArray(normalsData, index);
  23668. finalMatrix.reset();
  23669. }
  23670. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23671. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23672. return this;
  23673. };
  23674. // Tools
  23675. /**
  23676. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23677. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23678. */
  23679. Mesh.MinMax = function (meshes) {
  23680. var minVector = null;
  23681. var maxVector = null;
  23682. meshes.forEach(function (mesh, index, array) {
  23683. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23684. if (!minVector) {
  23685. minVector = boundingBox.minimumWorld;
  23686. maxVector = boundingBox.maximumWorld;
  23687. }
  23688. else {
  23689. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23690. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23691. }
  23692. });
  23693. return {
  23694. min: minVector,
  23695. max: maxVector
  23696. };
  23697. };
  23698. /**
  23699. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23700. */
  23701. Mesh.Center = function (meshesOrMinMaxVector) {
  23702. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23703. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23704. };
  23705. /**
  23706. * Merge the array of meshes into a single mesh for performance reasons.
  23707. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23708. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23709. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23710. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23711. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23712. */
  23713. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23714. if (disposeSource === void 0) { disposeSource = true; }
  23715. var index;
  23716. if (!allow32BitsIndices) {
  23717. var totalVertices = 0;
  23718. // Counting vertices
  23719. for (index = 0; index < meshes.length; index++) {
  23720. if (meshes[index]) {
  23721. totalVertices += meshes[index].getTotalVertices();
  23722. if (totalVertices > 65536) {
  23723. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  23724. return null;
  23725. }
  23726. }
  23727. }
  23728. }
  23729. // Merge
  23730. var vertexData;
  23731. var otherVertexData;
  23732. var indiceArray = new Array();
  23733. var source;
  23734. for (index = 0; index < meshes.length; index++) {
  23735. if (meshes[index]) {
  23736. meshes[index].computeWorldMatrix(true);
  23737. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23738. otherVertexData.transform(meshes[index].getWorldMatrix());
  23739. if (vertexData) {
  23740. vertexData.merge(otherVertexData);
  23741. }
  23742. else {
  23743. vertexData = otherVertexData;
  23744. source = meshes[index];
  23745. }
  23746. if (subdivideWithSubMeshes) {
  23747. indiceArray.push(meshes[index].getTotalIndices());
  23748. }
  23749. }
  23750. }
  23751. if (!meshSubclass) {
  23752. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23753. }
  23754. vertexData.applyToMesh(meshSubclass);
  23755. // Setting properties
  23756. meshSubclass.material = source.material;
  23757. meshSubclass.checkCollisions = source.checkCollisions;
  23758. // Cleaning
  23759. if (disposeSource) {
  23760. for (index = 0; index < meshes.length; index++) {
  23761. if (meshes[index]) {
  23762. meshes[index].dispose();
  23763. }
  23764. }
  23765. }
  23766. // Subdivide
  23767. if (subdivideWithSubMeshes) {
  23768. //-- Suppresions du submesh global
  23769. meshSubclass.releaseSubMeshes();
  23770. index = 0;
  23771. var offset = 0;
  23772. //-- aplique la subdivision en fonction du tableau d'indices
  23773. while (index < indiceArray.length) {
  23774. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  23775. offset += indiceArray[index];
  23776. index++;
  23777. }
  23778. }
  23779. return meshSubclass;
  23780. };
  23781. // Consts
  23782. Mesh._FRONTSIDE = 0;
  23783. Mesh._BACKSIDE = 1;
  23784. Mesh._DOUBLESIDE = 2;
  23785. Mesh._DEFAULTSIDE = 0;
  23786. Mesh._NO_CAP = 0;
  23787. Mesh._CAP_START = 1;
  23788. Mesh._CAP_END = 2;
  23789. Mesh._CAP_ALL = 3;
  23790. return Mesh;
  23791. }(BABYLON.AbstractMesh));
  23792. BABYLON.Mesh = Mesh;
  23793. })(BABYLON || (BABYLON = {}));
  23794. //# sourceMappingURL=babylon.mesh.js.map
  23795. var BABYLON;
  23796. (function (BABYLON) {
  23797. var BaseSubMesh = (function () {
  23798. function BaseSubMesh() {
  23799. }
  23800. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  23801. get: function () {
  23802. return this._materialEffect;
  23803. },
  23804. enumerable: true,
  23805. configurable: true
  23806. });
  23807. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  23808. if (this._materialEffect === effect) {
  23809. if (!effect) {
  23810. this._materialDefines = undefined;
  23811. }
  23812. return;
  23813. }
  23814. this._materialDefines = defines;
  23815. this._materialEffect = effect;
  23816. };
  23817. return BaseSubMesh;
  23818. }());
  23819. BABYLON.BaseSubMesh = BaseSubMesh;
  23820. var SubMesh = (function (_super) {
  23821. __extends(SubMesh, _super);
  23822. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  23823. if (createBoundingBox === void 0) { createBoundingBox = true; }
  23824. var _this = _super.call(this) || this;
  23825. _this.materialIndex = materialIndex;
  23826. _this.verticesStart = verticesStart;
  23827. _this.verticesCount = verticesCount;
  23828. _this.indexStart = indexStart;
  23829. _this.indexCount = indexCount;
  23830. _this._renderId = 0;
  23831. _this._mesh = mesh;
  23832. _this._renderingMesh = renderingMesh || mesh;
  23833. mesh.subMeshes.push(_this);
  23834. _this._trianglePlanes = [];
  23835. _this._id = mesh.subMeshes.length - 1;
  23836. if (createBoundingBox) {
  23837. _this.refreshBoundingInfo();
  23838. mesh.computeWorldMatrix(true);
  23839. }
  23840. return _this;
  23841. }
  23842. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  23843. get: function () {
  23844. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  23845. },
  23846. enumerable: true,
  23847. configurable: true
  23848. });
  23849. /**
  23850. * Returns the submesh BoudingInfo object.
  23851. */
  23852. SubMesh.prototype.getBoundingInfo = function () {
  23853. if (this.IsGlobal) {
  23854. return this._mesh.getBoundingInfo();
  23855. }
  23856. return this._boundingInfo;
  23857. };
  23858. /**
  23859. * Sets the submesh BoundingInfo.
  23860. * Return the SubMesh.
  23861. */
  23862. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  23863. this._boundingInfo = boundingInfo;
  23864. return this;
  23865. };
  23866. /**
  23867. * Returns the mesh of the current submesh.
  23868. */
  23869. SubMesh.prototype.getMesh = function () {
  23870. return this._mesh;
  23871. };
  23872. /**
  23873. * Returns the rendering mesh of the submesh.
  23874. */
  23875. SubMesh.prototype.getRenderingMesh = function () {
  23876. return this._renderingMesh;
  23877. };
  23878. /**
  23879. * Returns the submesh material.
  23880. */
  23881. SubMesh.prototype.getMaterial = function () {
  23882. var rootMaterial = this._renderingMesh.material;
  23883. if (rootMaterial && rootMaterial.getSubMaterial) {
  23884. var multiMaterial = rootMaterial;
  23885. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  23886. if (this._currentMaterial !== effectiveMaterial) {
  23887. this._currentMaterial = effectiveMaterial;
  23888. this._materialDefines = undefined;
  23889. }
  23890. return effectiveMaterial;
  23891. }
  23892. if (!rootMaterial) {
  23893. return this._mesh.getScene().defaultMaterial;
  23894. }
  23895. return rootMaterial;
  23896. };
  23897. // Methods
  23898. /**
  23899. * Sets a new updated BoundingInfo object to the submesh.
  23900. * Returns the SubMesh.
  23901. */
  23902. SubMesh.prototype.refreshBoundingInfo = function () {
  23903. this._lastColliderWorldVertices = null;
  23904. if (this.IsGlobal) {
  23905. return;
  23906. }
  23907. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23908. if (!data) {
  23909. this._boundingInfo = this._mesh._boundingInfo;
  23910. return;
  23911. }
  23912. var indices = this._renderingMesh.getIndices();
  23913. var extend;
  23914. //is this the only submesh?
  23915. if (this.indexStart === 0 && this.indexCount === indices.length) {
  23916. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  23917. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  23918. }
  23919. else {
  23920. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  23921. }
  23922. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23923. return this;
  23924. };
  23925. SubMesh.prototype._checkCollision = function (collider) {
  23926. return this.getBoundingInfo()._checkCollision(collider);
  23927. };
  23928. /**
  23929. * Updates the submesh BoundingInfo.
  23930. * Returns the Submesh.
  23931. */
  23932. SubMesh.prototype.updateBoundingInfo = function (world) {
  23933. if (!this.getBoundingInfo()) {
  23934. this.refreshBoundingInfo();
  23935. }
  23936. this.getBoundingInfo().update(world);
  23937. return this;
  23938. };
  23939. /**
  23940. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  23941. * Boolean returned.
  23942. */
  23943. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  23944. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  23945. };
  23946. /**
  23947. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  23948. * Boolean returned.
  23949. */
  23950. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  23951. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  23952. };
  23953. /**
  23954. * Renders the submesh.
  23955. * Returns it.
  23956. */
  23957. SubMesh.prototype.render = function (enableAlphaMode) {
  23958. this._renderingMesh.render(this, enableAlphaMode);
  23959. return this;
  23960. };
  23961. /**
  23962. * Returns a new Index Buffer.
  23963. * Type returned : WebGLBuffer.
  23964. */
  23965. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  23966. if (!this._linesIndexBuffer) {
  23967. var linesIndices = [];
  23968. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23969. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  23970. }
  23971. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  23972. this.linesIndexCount = linesIndices.length;
  23973. }
  23974. return this._linesIndexBuffer;
  23975. };
  23976. /**
  23977. * True is the passed Ray intersects the submesh bounding box.
  23978. * Boolean returned.
  23979. */
  23980. SubMesh.prototype.canIntersects = function (ray) {
  23981. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  23982. };
  23983. /**
  23984. * Returns an object IntersectionInfo.
  23985. */
  23986. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  23987. var intersectInfo = null;
  23988. // LineMesh first as it's also a Mesh...
  23989. if (this._mesh instanceof BABYLON.LinesMesh) {
  23990. var lineMesh = this._mesh;
  23991. // Line test
  23992. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  23993. var p0 = positions[indices[index]];
  23994. var p1 = positions[indices[index + 1]];
  23995. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  23996. if (length < 0) {
  23997. continue;
  23998. }
  23999. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  24000. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  24001. if (fastCheck) {
  24002. break;
  24003. }
  24004. }
  24005. }
  24006. }
  24007. else {
  24008. // Triangles test
  24009. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24010. var p0 = positions[indices[index]];
  24011. var p1 = positions[indices[index + 1]];
  24012. var p2 = positions[indices[index + 2]];
  24013. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24014. if (currentIntersectInfo) {
  24015. if (currentIntersectInfo.distance < 0) {
  24016. continue;
  24017. }
  24018. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24019. intersectInfo = currentIntersectInfo;
  24020. intersectInfo.faceId = index / 3;
  24021. if (fastCheck) {
  24022. break;
  24023. }
  24024. }
  24025. }
  24026. }
  24027. }
  24028. return intersectInfo;
  24029. };
  24030. SubMesh.prototype._rebuild = function () {
  24031. if (this._linesIndexBuffer) {
  24032. this._linesIndexBuffer = null;
  24033. }
  24034. };
  24035. // Clone
  24036. /**
  24037. * Creates a new Submesh from the passed Mesh.
  24038. */
  24039. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24040. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24041. if (!this.IsGlobal) {
  24042. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  24043. }
  24044. return result;
  24045. };
  24046. // Dispose
  24047. /**
  24048. * Disposes the Submesh.
  24049. * Returns nothing.
  24050. */
  24051. SubMesh.prototype.dispose = function () {
  24052. if (this._linesIndexBuffer) {
  24053. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  24054. this._linesIndexBuffer = null;
  24055. }
  24056. // Remove from mesh
  24057. var index = this._mesh.subMeshes.indexOf(this);
  24058. this._mesh.subMeshes.splice(index, 1);
  24059. };
  24060. // Statics
  24061. /**
  24062. * Creates a new Submesh from the passed parameters :
  24063. * - materialIndex (integer) : the index of the main mesh material.
  24064. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  24065. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  24066. * - mesh (Mesh) : the main mesh to create the submesh from.
  24067. * - renderingMesh (optional Mesh) : rendering mesh.
  24068. */
  24069. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  24070. var minVertexIndex = Number.MAX_VALUE;
  24071. var maxVertexIndex = -Number.MAX_VALUE;
  24072. renderingMesh = renderingMesh || mesh;
  24073. var indices = renderingMesh.getIndices();
  24074. for (var index = startIndex; index < startIndex + indexCount; index++) {
  24075. var vertexIndex = indices[index];
  24076. if (vertexIndex < minVertexIndex)
  24077. minVertexIndex = vertexIndex;
  24078. if (vertexIndex > maxVertexIndex)
  24079. maxVertexIndex = vertexIndex;
  24080. }
  24081. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  24082. };
  24083. return SubMesh;
  24084. }(BaseSubMesh));
  24085. BABYLON.SubMesh = SubMesh;
  24086. })(BABYLON || (BABYLON = {}));
  24087. //# sourceMappingURL=babylon.subMesh.js.map
  24088. var BABYLON;
  24089. (function (BABYLON) {
  24090. var EffectFallbacks = (function () {
  24091. function EffectFallbacks() {
  24092. this._defines = {};
  24093. this._currentRank = 32;
  24094. this._maxRank = -1;
  24095. }
  24096. EffectFallbacks.prototype.unBindMesh = function () {
  24097. this._mesh = null;
  24098. };
  24099. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24100. if (!this._defines[rank]) {
  24101. if (rank < this._currentRank) {
  24102. this._currentRank = rank;
  24103. }
  24104. if (rank > this._maxRank) {
  24105. this._maxRank = rank;
  24106. }
  24107. this._defines[rank] = new Array();
  24108. }
  24109. this._defines[rank].push(define);
  24110. };
  24111. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24112. this._meshRank = rank;
  24113. this._mesh = mesh;
  24114. if (rank < this._currentRank) {
  24115. this._currentRank = rank;
  24116. }
  24117. if (rank > this._maxRank) {
  24118. this._maxRank = rank;
  24119. }
  24120. };
  24121. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24122. get: function () {
  24123. return this._currentRank <= this._maxRank;
  24124. },
  24125. enumerable: true,
  24126. configurable: true
  24127. });
  24128. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24129. // First we try to switch to CPU skinning
  24130. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  24131. this._mesh.computeBonesUsingShaders = false;
  24132. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24133. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24134. var scene = this._mesh.getScene();
  24135. for (var index = 0; index < scene.meshes.length; index++) {
  24136. var otherMesh = scene.meshes[index];
  24137. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  24138. otherMesh.computeBonesUsingShaders = false;
  24139. }
  24140. }
  24141. }
  24142. else {
  24143. var currentFallbacks = this._defines[this._currentRank];
  24144. if (currentFallbacks) {
  24145. for (var index = 0; index < currentFallbacks.length; index++) {
  24146. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24147. }
  24148. }
  24149. this._currentRank++;
  24150. }
  24151. return currentDefines;
  24152. };
  24153. return EffectFallbacks;
  24154. }());
  24155. BABYLON.EffectFallbacks = EffectFallbacks;
  24156. var EffectCreationOptions = (function () {
  24157. function EffectCreationOptions() {
  24158. }
  24159. return EffectCreationOptions;
  24160. }());
  24161. BABYLON.EffectCreationOptions = EffectCreationOptions;
  24162. var Effect = (function () {
  24163. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24164. var _this = this;
  24165. this.uniqueId = 0;
  24166. this.onCompileObservable = new BABYLON.Observable();
  24167. this.onErrorObservable = new BABYLON.Observable();
  24168. this.onBindObservable = new BABYLON.Observable();
  24169. this._uniformBuffersNames = {};
  24170. this._isReady = false;
  24171. this._compilationError = "";
  24172. this.name = baseName;
  24173. if (attributesNamesOrOptions.attributes) {
  24174. var options = attributesNamesOrOptions;
  24175. this._engine = uniformsNamesOrEngine;
  24176. this._attributesNames = options.attributes;
  24177. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24178. this._samplers = options.samplers;
  24179. this.defines = options.defines;
  24180. this.onError = options.onError;
  24181. this.onCompiled = options.onCompiled;
  24182. this._fallbacks = options.fallbacks;
  24183. this._indexParameters = options.indexParameters;
  24184. if (options.uniformBuffersNames) {
  24185. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24186. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24187. }
  24188. }
  24189. }
  24190. else {
  24191. this._engine = engine;
  24192. this.defines = defines;
  24193. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24194. this._samplers = samplers;
  24195. this._attributesNames = attributesNamesOrOptions;
  24196. this.onError = onError;
  24197. this.onCompiled = onCompiled;
  24198. this._indexParameters = indexParameters;
  24199. this._fallbacks = fallbacks;
  24200. }
  24201. this.uniqueId = Effect._uniqueIdSeed++;
  24202. var vertexSource;
  24203. var fragmentSource;
  24204. if (baseName.vertexElement) {
  24205. vertexSource = document.getElementById(baseName.vertexElement);
  24206. if (!vertexSource) {
  24207. vertexSource = baseName.vertexElement;
  24208. }
  24209. }
  24210. else {
  24211. vertexSource = baseName.vertex || baseName;
  24212. }
  24213. if (baseName.fragmentElement) {
  24214. fragmentSource = document.getElementById(baseName.fragmentElement);
  24215. if (!fragmentSource) {
  24216. fragmentSource = baseName.fragmentElement;
  24217. }
  24218. }
  24219. else {
  24220. fragmentSource = baseName.fragment || baseName;
  24221. }
  24222. this._loadVertexShader(vertexSource, function (vertexCode) {
  24223. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24224. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24225. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24226. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24227. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24228. if (baseName) {
  24229. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + migratedVertexCode;
  24230. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + migratedFragmentCode;
  24231. }
  24232. else {
  24233. _this._vertexSourceCode = migratedVertexCode;
  24234. _this._fragmentSourceCode = migratedFragmentCode;
  24235. }
  24236. _this._prepareEffect();
  24237. });
  24238. });
  24239. });
  24240. });
  24241. });
  24242. });
  24243. }
  24244. Object.defineProperty(Effect.prototype, "key", {
  24245. get: function () {
  24246. return this._key;
  24247. },
  24248. enumerable: true,
  24249. configurable: true
  24250. });
  24251. // Properties
  24252. Effect.prototype.isReady = function () {
  24253. return this._isReady;
  24254. };
  24255. Effect.prototype.getEngine = function () {
  24256. return this._engine;
  24257. };
  24258. Effect.prototype.getProgram = function () {
  24259. return this._program;
  24260. };
  24261. Effect.prototype.getAttributesNames = function () {
  24262. return this._attributesNames;
  24263. };
  24264. Effect.prototype.getAttributeLocation = function (index) {
  24265. return this._attributes[index];
  24266. };
  24267. Effect.prototype.getAttributeLocationByName = function (name) {
  24268. var index = this._attributesNames.indexOf(name);
  24269. return this._attributes[index];
  24270. };
  24271. Effect.prototype.getAttributesCount = function () {
  24272. return this._attributes.length;
  24273. };
  24274. Effect.prototype.getUniformIndex = function (uniformName) {
  24275. return this._uniformsNames.indexOf(uniformName);
  24276. };
  24277. Effect.prototype.getUniform = function (uniformName) {
  24278. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24279. };
  24280. Effect.prototype.getSamplers = function () {
  24281. return this._samplers;
  24282. };
  24283. Effect.prototype.getCompilationError = function () {
  24284. return this._compilationError;
  24285. };
  24286. // Methods
  24287. Effect.prototype.executeWhenCompiled = function (func) {
  24288. if (this.isReady()) {
  24289. func(this);
  24290. return;
  24291. }
  24292. this.onCompileObservable.add(function (effect) {
  24293. func(effect);
  24294. });
  24295. };
  24296. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24297. // DOM element ?
  24298. if (vertex instanceof HTMLElement) {
  24299. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24300. callback(vertexCode);
  24301. return;
  24302. }
  24303. // Base64 encoded ?
  24304. if (vertex.substr(0, 7) === "base64:") {
  24305. var vertexBinary = window.atob(vertex.substr(7));
  24306. callback(vertexBinary);
  24307. return;
  24308. }
  24309. // Is in local store ?
  24310. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24311. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24312. return;
  24313. }
  24314. var vertexShaderUrl;
  24315. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24316. vertexShaderUrl = vertex;
  24317. }
  24318. else {
  24319. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24320. }
  24321. // Vertex shader
  24322. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24323. };
  24324. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24325. // DOM element ?
  24326. if (fragment instanceof HTMLElement) {
  24327. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24328. callback(fragmentCode);
  24329. return;
  24330. }
  24331. // Base64 encoded ?
  24332. if (fragment.substr(0, 7) === "base64:") {
  24333. var fragmentBinary = window.atob(fragment.substr(7));
  24334. callback(fragmentBinary);
  24335. return;
  24336. }
  24337. // Is in local store ?
  24338. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24339. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24340. return;
  24341. }
  24342. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24343. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24344. return;
  24345. }
  24346. var fragmentShaderUrl;
  24347. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24348. fragmentShaderUrl = fragment;
  24349. }
  24350. else {
  24351. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24352. }
  24353. // Fragment shader
  24354. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24355. };
  24356. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24357. // Rebuild shaders source code
  24358. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24359. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24360. vertexCode = prefix + vertexCode;
  24361. fragmentCode = prefix + fragmentCode;
  24362. // Number lines of shaders source code
  24363. var i = 2;
  24364. var regex = /\n/gm;
  24365. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24366. i = 2;
  24367. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24368. // Dump shaders name and formatted source code
  24369. if (this.name.vertexElement) {
  24370. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24371. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24372. }
  24373. else if (this.name.vertex) {
  24374. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24375. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24376. }
  24377. else {
  24378. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24379. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24380. }
  24381. };
  24382. ;
  24383. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24384. var preparedSourceCode = this._processPrecision(sourceCode);
  24385. if (this._engine.webGLVersion == 1) {
  24386. callback(preparedSourceCode);
  24387. return;
  24388. }
  24389. // Already converted
  24390. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24391. callback(preparedSourceCode.replace("#version 300 es", ""));
  24392. return;
  24393. }
  24394. // Remove extensions
  24395. // #extension GL_OES_standard_derivatives : enable
  24396. // #extension GL_EXT_shader_texture_lod : enable
  24397. // #extension GL_EXT_frag_depth : enable
  24398. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  24399. var result = preparedSourceCode.replace(regex, "");
  24400. // Migrate to GLSL v300
  24401. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24402. result = result.replace(/attribute[ \t]/g, "in ");
  24403. result = result.replace(/[ \t]attribute/g, " in");
  24404. if (isFragment) {
  24405. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  24406. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  24407. result = result.replace(/texture2D\(/g, "texture(");
  24408. result = result.replace(/textureCube\(/g, "texture(");
  24409. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24410. result = result.replace(/gl_FragColor/g, "glFragColor");
  24411. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  24412. }
  24413. callback(result);
  24414. };
  24415. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24416. var _this = this;
  24417. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24418. var match = regex.exec(sourceCode);
  24419. var returnValue = new String(sourceCode);
  24420. while (match != null) {
  24421. var includeFile = match[1];
  24422. // Uniform declaration
  24423. if (includeFile.indexOf("__decl__") !== -1) {
  24424. includeFile = includeFile.replace(/__decl__/, "");
  24425. if (this._engine.supportsUniformBuffers) {
  24426. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24427. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24428. }
  24429. includeFile = includeFile + "Declaration";
  24430. }
  24431. if (Effect.IncludesShadersStore[includeFile]) {
  24432. // Substitution
  24433. var includeContent = Effect.IncludesShadersStore[includeFile];
  24434. if (match[2]) {
  24435. var splits = match[3].split(",");
  24436. for (var index = 0; index < splits.length; index += 2) {
  24437. var source = new RegExp(splits[index], "g");
  24438. var dest = splits[index + 1];
  24439. includeContent = includeContent.replace(source, dest);
  24440. }
  24441. }
  24442. if (match[4]) {
  24443. var indexString = match[5];
  24444. if (indexString.indexOf("..") !== -1) {
  24445. var indexSplits = indexString.split("..");
  24446. var minIndex = parseInt(indexSplits[0]);
  24447. var maxIndex = parseInt(indexSplits[1]);
  24448. var sourceIncludeContent = includeContent.slice(0);
  24449. includeContent = "";
  24450. if (isNaN(maxIndex)) {
  24451. maxIndex = this._indexParameters[indexSplits[1]];
  24452. }
  24453. for (var i = minIndex; i < maxIndex; i++) {
  24454. if (!this._engine.supportsUniformBuffers) {
  24455. // Ubo replacement
  24456. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24457. return p1 + "{X}";
  24458. });
  24459. }
  24460. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24461. }
  24462. }
  24463. else {
  24464. if (!this._engine.supportsUniformBuffers) {
  24465. // Ubo replacement
  24466. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24467. return p1 + "{X}";
  24468. });
  24469. }
  24470. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24471. }
  24472. }
  24473. // Replace
  24474. returnValue = returnValue.replace(match[0], includeContent);
  24475. }
  24476. else {
  24477. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24478. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24479. Effect.IncludesShadersStore[includeFile] = fileContent;
  24480. _this._processIncludes(returnValue, callback);
  24481. });
  24482. return;
  24483. }
  24484. match = regex.exec(sourceCode);
  24485. }
  24486. callback(returnValue);
  24487. };
  24488. Effect.prototype._processPrecision = function (source) {
  24489. if (source.indexOf("precision highp float") === -1) {
  24490. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24491. source = "precision mediump float;\n" + source;
  24492. }
  24493. else {
  24494. source = "precision highp float;\n" + source;
  24495. }
  24496. }
  24497. else {
  24498. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24499. source = source.replace("precision highp float", "precision mediump float");
  24500. }
  24501. }
  24502. return source;
  24503. };
  24504. Effect.prototype._prepareEffect = function () {
  24505. var attributesNames = this._attributesNames;
  24506. var defines = this.defines;
  24507. var fallbacks = this._fallbacks;
  24508. this._valueCache = {};
  24509. try {
  24510. var engine = this._engine;
  24511. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24512. if (engine.webGLVersion > 1) {
  24513. for (var name in this._uniformBuffersNames) {
  24514. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24515. }
  24516. }
  24517. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24518. this._attributes = engine.getAttributes(this._program, attributesNames);
  24519. var index;
  24520. for (index = 0; index < this._samplers.length; index++) {
  24521. var sampler = this.getUniform(this._samplers[index]);
  24522. if (sampler == null) {
  24523. this._samplers.splice(index, 1);
  24524. index--;
  24525. }
  24526. }
  24527. engine.bindSamplers(this);
  24528. this._compilationError = "";
  24529. this._isReady = true;
  24530. if (this.onCompiled) {
  24531. this.onCompiled(this);
  24532. }
  24533. this.onCompileObservable.notifyObservers(this);
  24534. this.onCompileObservable.clear();
  24535. // Unbind mesh reference in fallbacks
  24536. if (this._fallbacks) {
  24537. this._fallbacks.unBindMesh();
  24538. }
  24539. }
  24540. catch (e) {
  24541. this._compilationError = e.message;
  24542. // Let's go through fallbacks then
  24543. BABYLON.Tools.Error("Unable to compile effect:");
  24544. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24545. return " " + uniform;
  24546. }));
  24547. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24548. return " " + attribute;
  24549. }));
  24550. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24551. BABYLON.Tools.Error("Error: " + this._compilationError);
  24552. if (fallbacks && fallbacks.isMoreFallbacks) {
  24553. BABYLON.Tools.Error("Trying next fallback.");
  24554. this.defines = fallbacks.reduce(this.defines);
  24555. this._prepareEffect();
  24556. }
  24557. else {
  24558. if (this.onError) {
  24559. this.onError(this, this._compilationError);
  24560. }
  24561. this.onErrorObservable.notifyObservers(this);
  24562. this.onErrorObservable.clear();
  24563. // Unbind mesh reference in fallbacks
  24564. if (this._fallbacks) {
  24565. this._fallbacks.unBindMesh();
  24566. }
  24567. }
  24568. }
  24569. };
  24570. Object.defineProperty(Effect.prototype, "isSupported", {
  24571. get: function () {
  24572. return this._compilationError === "";
  24573. },
  24574. enumerable: true,
  24575. configurable: true
  24576. });
  24577. Effect.prototype._bindTexture = function (channel, texture) {
  24578. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24579. };
  24580. Effect.prototype.setTexture = function (channel, texture) {
  24581. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24582. };
  24583. Effect.prototype.setTextureArray = function (channel, textures) {
  24584. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24585. var initialPos = this._samplers.indexOf(channel);
  24586. for (var index = 1; index < textures.length; index++) {
  24587. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24588. }
  24589. }
  24590. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24591. };
  24592. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24593. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24594. };
  24595. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24596. var cache = this._valueCache[uniformName];
  24597. var flag = matrix.updateFlag;
  24598. if (cache !== undefined && cache === flag) {
  24599. return false;
  24600. }
  24601. this._valueCache[uniformName] = flag;
  24602. return true;
  24603. };
  24604. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24605. var cache = this._valueCache[uniformName];
  24606. if (!cache) {
  24607. cache = [x, y];
  24608. this._valueCache[uniformName] = cache;
  24609. return true;
  24610. }
  24611. var changed = false;
  24612. if (cache[0] !== x) {
  24613. cache[0] = x;
  24614. changed = true;
  24615. }
  24616. if (cache[1] !== y) {
  24617. cache[1] = y;
  24618. changed = true;
  24619. }
  24620. return changed;
  24621. };
  24622. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24623. var cache = this._valueCache[uniformName];
  24624. if (!cache) {
  24625. cache = [x, y, z];
  24626. this._valueCache[uniformName] = cache;
  24627. return true;
  24628. }
  24629. var changed = false;
  24630. if (cache[0] !== x) {
  24631. cache[0] = x;
  24632. changed = true;
  24633. }
  24634. if (cache[1] !== y) {
  24635. cache[1] = y;
  24636. changed = true;
  24637. }
  24638. if (cache[2] !== z) {
  24639. cache[2] = z;
  24640. changed = true;
  24641. }
  24642. return changed;
  24643. };
  24644. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24645. var cache = this._valueCache[uniformName];
  24646. if (!cache) {
  24647. cache = [x, y, z, w];
  24648. this._valueCache[uniformName] = cache;
  24649. return true;
  24650. }
  24651. var changed = false;
  24652. if (cache[0] !== x) {
  24653. cache[0] = x;
  24654. changed = true;
  24655. }
  24656. if (cache[1] !== y) {
  24657. cache[1] = y;
  24658. changed = true;
  24659. }
  24660. if (cache[2] !== z) {
  24661. cache[2] = z;
  24662. changed = true;
  24663. }
  24664. if (cache[3] !== w) {
  24665. cache[3] = w;
  24666. changed = true;
  24667. }
  24668. return changed;
  24669. };
  24670. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  24671. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  24672. return;
  24673. }
  24674. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  24675. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  24676. };
  24677. Effect.prototype.bindUniformBlock = function (blockName, index) {
  24678. this._engine.bindUniformBlock(this._program, blockName, index);
  24679. };
  24680. Effect.prototype.setIntArray = function (uniformName, array) {
  24681. this._valueCache[uniformName] = null;
  24682. this._engine.setIntArray(this.getUniform(uniformName), array);
  24683. return this;
  24684. };
  24685. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24686. this._valueCache[uniformName] = null;
  24687. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24688. return this;
  24689. };
  24690. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24691. this._valueCache[uniformName] = null;
  24692. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24693. return this;
  24694. };
  24695. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24696. this._valueCache[uniformName] = null;
  24697. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24698. return this;
  24699. };
  24700. Effect.prototype.setFloatArray = function (uniformName, array) {
  24701. this._valueCache[uniformName] = null;
  24702. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24703. return this;
  24704. };
  24705. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24706. this._valueCache[uniformName] = null;
  24707. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24708. return this;
  24709. };
  24710. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24711. this._valueCache[uniformName] = null;
  24712. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24713. return this;
  24714. };
  24715. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24716. this._valueCache[uniformName] = null;
  24717. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24718. return this;
  24719. };
  24720. Effect.prototype.setArray = function (uniformName, array) {
  24721. this._valueCache[uniformName] = null;
  24722. this._engine.setArray(this.getUniform(uniformName), array);
  24723. return this;
  24724. };
  24725. Effect.prototype.setArray2 = function (uniformName, array) {
  24726. this._valueCache[uniformName] = null;
  24727. this._engine.setArray2(this.getUniform(uniformName), array);
  24728. return this;
  24729. };
  24730. Effect.prototype.setArray3 = function (uniformName, array) {
  24731. this._valueCache[uniformName] = null;
  24732. this._engine.setArray3(this.getUniform(uniformName), array);
  24733. return this;
  24734. };
  24735. Effect.prototype.setArray4 = function (uniformName, array) {
  24736. this._valueCache[uniformName] = null;
  24737. this._engine.setArray4(this.getUniform(uniformName), array);
  24738. return this;
  24739. };
  24740. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24741. if (!matrices) {
  24742. return;
  24743. }
  24744. this._valueCache[uniformName] = null;
  24745. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24746. return this;
  24747. };
  24748. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24749. if (this._cacheMatrix(uniformName, matrix)) {
  24750. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24751. }
  24752. return this;
  24753. };
  24754. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24755. this._valueCache[uniformName] = null;
  24756. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24757. return this;
  24758. };
  24759. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24760. this._valueCache[uniformName] = null;
  24761. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24762. return this;
  24763. };
  24764. Effect.prototype.setFloat = function (uniformName, value) {
  24765. var cache = this._valueCache[uniformName];
  24766. if (cache !== undefined && cache === value)
  24767. return this;
  24768. this._valueCache[uniformName] = value;
  24769. this._engine.setFloat(this.getUniform(uniformName), value);
  24770. return this;
  24771. };
  24772. Effect.prototype.setBool = function (uniformName, bool) {
  24773. var cache = this._valueCache[uniformName];
  24774. if (cache !== undefined && cache === bool)
  24775. return this;
  24776. this._valueCache[uniformName] = bool;
  24777. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24778. return this;
  24779. };
  24780. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24781. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24782. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24783. }
  24784. return this;
  24785. };
  24786. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24787. if (this._cacheFloat2(uniformName, x, y)) {
  24788. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24789. }
  24790. return this;
  24791. };
  24792. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24793. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24794. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24795. }
  24796. return this;
  24797. };
  24798. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24799. if (this._cacheFloat3(uniformName, x, y, z)) {
  24800. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24801. }
  24802. return this;
  24803. };
  24804. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24805. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24806. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24807. }
  24808. return this;
  24809. };
  24810. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24811. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24812. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24813. }
  24814. return this;
  24815. };
  24816. Effect.prototype.setColor3 = function (uniformName, color3) {
  24817. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24818. this._engine.setColor3(this.getUniform(uniformName), color3);
  24819. }
  24820. return this;
  24821. };
  24822. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24823. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24824. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24825. }
  24826. return this;
  24827. };
  24828. Effect.ResetCache = function () {
  24829. Effect._baseCache = {};
  24830. };
  24831. Effect._uniqueIdSeed = 0;
  24832. Effect._baseCache = {};
  24833. // Statics
  24834. Effect.ShadersStore = {};
  24835. Effect.IncludesShadersStore = {};
  24836. return Effect;
  24837. }());
  24838. BABYLON.Effect = Effect;
  24839. })(BABYLON || (BABYLON = {}));
  24840. //# sourceMappingURL=babylon.effect.js.map
  24841. var BABYLON;
  24842. (function (BABYLON) {
  24843. var MaterialHelper = (function () {
  24844. function MaterialHelper() {
  24845. }
  24846. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  24847. defines._needUVs = true;
  24848. defines[key] = true;
  24849. if (texture.getTextureMatrix().isIdentity(true)) {
  24850. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  24851. if (texture.coordinatesIndex === 0) {
  24852. defines["MAINUV1"] = true;
  24853. }
  24854. else {
  24855. defines["MAINUV2"] = true;
  24856. }
  24857. }
  24858. else {
  24859. defines[key + "DIRECTUV"] = 0;
  24860. }
  24861. };
  24862. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  24863. var matrix = texture.getTextureMatrix();
  24864. if (!matrix.isIdentity(true)) {
  24865. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  24866. }
  24867. };
  24868. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  24869. if (defines._areMiscDirty) {
  24870. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  24871. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  24872. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  24873. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  24874. }
  24875. };
  24876. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  24877. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  24878. var changed = false;
  24879. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  24880. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  24881. changed = true;
  24882. }
  24883. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  24884. defines["ALPHATEST"] = !defines["ALPHATEST"];
  24885. changed = true;
  24886. }
  24887. if (defines["INSTANCES"] !== useInstances) {
  24888. defines["INSTANCES"] = useInstances;
  24889. changed = true;
  24890. }
  24891. if (changed) {
  24892. defines.markAsUnprocessed();
  24893. }
  24894. };
  24895. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  24896. if (useMorphTargets === void 0) { useMorphTargets = false; }
  24897. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  24898. return false;
  24899. }
  24900. defines._normals = defines._needNormals;
  24901. defines._uvs = defines._needUVs;
  24902. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  24903. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24904. defines["TANGENT"] = true;
  24905. }
  24906. if (defines._needUVs) {
  24907. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  24908. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  24909. }
  24910. else {
  24911. defines["UV1"] = false;
  24912. defines["UV2"] = false;
  24913. }
  24914. if (useVertexColor) {
  24915. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  24916. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  24917. }
  24918. if (useBones) {
  24919. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24920. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  24921. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  24922. }
  24923. else {
  24924. defines["NUM_BONE_INFLUENCERS"] = 0;
  24925. defines["BonesPerMesh"] = 0;
  24926. }
  24927. }
  24928. if (useMorphTargets) {
  24929. if (mesh.morphTargetManager) {
  24930. var manager = mesh.morphTargetManager;
  24931. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  24932. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  24933. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  24934. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  24935. }
  24936. else {
  24937. defines["MORPHTARGETS_TANGENT"] = false;
  24938. defines["MORPHTARGETS_NORMAL"] = false;
  24939. defines["MORPHTARGETS"] = false;
  24940. defines["NUM_MORPH_INFLUENCERS"] = 0;
  24941. }
  24942. }
  24943. return true;
  24944. };
  24945. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  24946. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24947. if (disableLighting === void 0) { disableLighting = false; }
  24948. if (!defines._areLightsDirty) {
  24949. return defines._needNormals;
  24950. }
  24951. var lightIndex = 0;
  24952. var needNormals = false;
  24953. var needRebuild = false;
  24954. var lightmapMode = false;
  24955. var shadowEnabled = false;
  24956. var specularEnabled = false;
  24957. if (scene.lightsEnabled && !disableLighting) {
  24958. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24959. var light = _a[_i];
  24960. needNormals = true;
  24961. if (defines["LIGHT" + lightIndex] === undefined) {
  24962. needRebuild = true;
  24963. }
  24964. defines["LIGHT" + lightIndex] = true;
  24965. defines["SPOTLIGHT" + lightIndex] = false;
  24966. defines["HEMILIGHT" + lightIndex] = false;
  24967. defines["POINTLIGHT" + lightIndex] = false;
  24968. defines["DIRLIGHT" + lightIndex] = false;
  24969. var type;
  24970. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  24971. type = "SPOTLIGHT" + lightIndex;
  24972. }
  24973. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  24974. type = "HEMILIGHT" + lightIndex;
  24975. }
  24976. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  24977. type = "POINTLIGHT" + lightIndex;
  24978. }
  24979. else {
  24980. type = "DIRLIGHT" + lightIndex;
  24981. }
  24982. defines[type] = true;
  24983. // Specular
  24984. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  24985. specularEnabled = true;
  24986. }
  24987. // Shadows
  24988. defines["SHADOW" + lightIndex] = false;
  24989. defines["SHADOWPCF" + lightIndex] = false;
  24990. defines["SHADOWESM" + lightIndex] = false;
  24991. defines["SHADOWCUBE" + lightIndex] = false;
  24992. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  24993. var shadowGenerator = light.getShadowGenerator();
  24994. if (shadowGenerator) {
  24995. shadowEnabled = true;
  24996. shadowGenerator.prepareDefines(defines, lightIndex);
  24997. }
  24998. }
  24999. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25000. lightmapMode = true;
  25001. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25002. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  25003. }
  25004. else {
  25005. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  25006. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  25007. }
  25008. lightIndex++;
  25009. if (lightIndex === maxSimultaneousLights)
  25010. break;
  25011. }
  25012. }
  25013. defines["SPECULARTERM"] = specularEnabled;
  25014. defines["SHADOWS"] = shadowEnabled;
  25015. // Resetting all other lights if any
  25016. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  25017. if (defines["LIGHT" + index] !== undefined) {
  25018. defines["LIGHT" + index] = false;
  25019. defines["HEMILIGHT" + lightIndex] = false;
  25020. defines["POINTLIGHT" + lightIndex] = false;
  25021. defines["DIRLIGHT" + lightIndex] = false;
  25022. defines["SPOTLIGHT" + lightIndex] = false;
  25023. defines["SHADOW" + lightIndex] = false;
  25024. }
  25025. }
  25026. var caps = scene.getEngine().getCaps();
  25027. if (defines["SHADOWFLOAT"] === undefined) {
  25028. needRebuild = true;
  25029. }
  25030. defines["SHADOWFLOAT"] = shadowEnabled &&
  25031. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  25032. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  25033. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  25034. if (needRebuild) {
  25035. defines.rebuild();
  25036. }
  25037. return needNormals;
  25038. };
  25039. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  25040. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25041. var uniformsList, uniformBuffersList, samplersList, defines;
  25042. if (uniformsListOrOptions.uniformsNames) {
  25043. var options = uniformsListOrOptions;
  25044. uniformsList = options.uniformsNames;
  25045. uniformBuffersList = options.uniformBuffersNames;
  25046. samplersList = options.samplers;
  25047. defines = options.defines;
  25048. maxSimultaneousLights = options.maxSimultaneousLights;
  25049. }
  25050. else {
  25051. uniformsList = uniformsListOrOptions;
  25052. }
  25053. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25054. if (!defines["LIGHT" + lightIndex]) {
  25055. break;
  25056. }
  25057. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  25058. if (uniformBuffersList) {
  25059. uniformBuffersList.push("Light" + lightIndex);
  25060. }
  25061. samplersList.push("shadowSampler" + lightIndex);
  25062. }
  25063. if (defines["NUM_MORPH_INFLUENCERS"]) {
  25064. uniformsList.push("morphTargetInfluences");
  25065. }
  25066. };
  25067. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25068. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25069. if (!defines["SHADOWS"]) {
  25070. return;
  25071. }
  25072. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25073. if (!defines["LIGHT" + lightIndex]) {
  25074. break;
  25075. }
  25076. if (lightIndex > 0) {
  25077. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25078. }
  25079. if (defines["SHADOW" + lightIndex]) {
  25080. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25081. }
  25082. if (defines["SHADOWPCF" + lightIndex]) {
  25083. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25084. }
  25085. if (defines["SHADOWESM" + lightIndex]) {
  25086. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  25087. }
  25088. }
  25089. };
  25090. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  25091. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  25092. if (influencers > 0) {
  25093. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  25094. var manager = mesh.morphTargetManager;
  25095. var normal = manager.supportsNormals && defines["NORMAL"];
  25096. var tangent = manager.supportsTangents && defines["TANGENT"];
  25097. for (var index = 0; index < influencers; index++) {
  25098. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  25099. if (normal) {
  25100. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  25101. }
  25102. if (tangent) {
  25103. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  25104. }
  25105. if (attribs.length > maxAttributesCount) {
  25106. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  25107. }
  25108. }
  25109. }
  25110. };
  25111. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25112. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25113. fallbacks.addCPUSkinningFallback(0, mesh);
  25114. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25115. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25116. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25117. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25118. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25119. }
  25120. }
  25121. };
  25122. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25123. if (defines["INSTANCES"]) {
  25124. attribs.push("world0");
  25125. attribs.push("world1");
  25126. attribs.push("world2");
  25127. attribs.push("world3");
  25128. }
  25129. };
  25130. // Bindings
  25131. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  25132. if (light.shadowEnabled && mesh.receiveShadows) {
  25133. var shadowGenerator = light.getShadowGenerator();
  25134. if (shadowGenerator) {
  25135. shadowGenerator.bindShadowLight(lightIndex, effect);
  25136. }
  25137. }
  25138. };
  25139. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25140. light.transferToEffect(effect, lightIndex + "");
  25141. };
  25142. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  25143. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25144. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  25145. var lightIndex = 0;
  25146. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25147. var light = _a[_i];
  25148. var scaledIntensity = light.getScaledIntensity();
  25149. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  25150. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25151. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  25152. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  25153. if (defines["SPECULARTERM"]) {
  25154. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  25155. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  25156. }
  25157. // Shadows
  25158. if (scene.shadowsEnabled) {
  25159. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  25160. }
  25161. light._uniformBuffer.update();
  25162. lightIndex++;
  25163. if (lightIndex === maxSimultaneousLights)
  25164. break;
  25165. }
  25166. };
  25167. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25168. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25169. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25170. effect.setColor3("vFogColor", scene.fogColor);
  25171. }
  25172. };
  25173. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25174. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25175. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25176. if (matrices) {
  25177. effect.setMatrices("mBones", matrices);
  25178. }
  25179. }
  25180. };
  25181. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25182. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25183. return;
  25184. }
  25185. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25186. };
  25187. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25188. if (defines["LOGARITHMICDEPTH"]) {
  25189. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25190. }
  25191. };
  25192. MaterialHelper.BindClipPlane = function (effect, scene) {
  25193. if (scene.clipPlane) {
  25194. var clipPlane = scene.clipPlane;
  25195. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25196. }
  25197. };
  25198. return MaterialHelper;
  25199. }());
  25200. BABYLON.MaterialHelper = MaterialHelper;
  25201. })(BABYLON || (BABYLON = {}));
  25202. //# sourceMappingURL=babylon.materialHelper.js.map
  25203. var BABYLON;
  25204. (function (BABYLON) {
  25205. var MaterialDefines = (function () {
  25206. function MaterialDefines() {
  25207. this._isDirty = true;
  25208. this._areLightsDirty = true;
  25209. this._areAttributesDirty = true;
  25210. this._areTexturesDirty = true;
  25211. this._areFresnelDirty = true;
  25212. this._areMiscDirty = true;
  25213. this._areImageProcessingDirty = true;
  25214. this._normals = false;
  25215. this._uvs = false;
  25216. this._needNormals = false;
  25217. this._needUVs = false;
  25218. }
  25219. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25220. get: function () {
  25221. return this._isDirty;
  25222. },
  25223. enumerable: true,
  25224. configurable: true
  25225. });
  25226. MaterialDefines.prototype.markAsProcessed = function () {
  25227. this._isDirty = false;
  25228. this._areAttributesDirty = false;
  25229. this._areTexturesDirty = false;
  25230. this._areFresnelDirty = false;
  25231. this._areLightsDirty = false;
  25232. this._areMiscDirty = false;
  25233. this._areImageProcessingDirty = false;
  25234. };
  25235. MaterialDefines.prototype.markAsUnprocessed = function () {
  25236. this._isDirty = true;
  25237. };
  25238. MaterialDefines.prototype.markAllAsDirty = function () {
  25239. this._areTexturesDirty = true;
  25240. this._areAttributesDirty = true;
  25241. this._areLightsDirty = true;
  25242. this._areFresnelDirty = true;
  25243. this._areMiscDirty = true;
  25244. this._areImageProcessingDirty = true;
  25245. this._isDirty = true;
  25246. };
  25247. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25248. this._areImageProcessingDirty = true;
  25249. this._isDirty = true;
  25250. };
  25251. MaterialDefines.prototype.markAsLightDirty = function () {
  25252. this._areLightsDirty = true;
  25253. this._isDirty = true;
  25254. };
  25255. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25256. this._areAttributesDirty = true;
  25257. this._isDirty = true;
  25258. };
  25259. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25260. this._areTexturesDirty = true;
  25261. this._isDirty = true;
  25262. };
  25263. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25264. this._areFresnelDirty = true;
  25265. this._isDirty = true;
  25266. };
  25267. MaterialDefines.prototype.markAsMiscDirty = function () {
  25268. this._areMiscDirty = true;
  25269. this._isDirty = true;
  25270. };
  25271. MaterialDefines.prototype.rebuild = function () {
  25272. if (this._keys) {
  25273. delete this._keys;
  25274. }
  25275. this._keys = [];
  25276. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25277. var key = _a[_i];
  25278. if (key[0] === "_") {
  25279. continue;
  25280. }
  25281. this._keys.push(key);
  25282. }
  25283. };
  25284. MaterialDefines.prototype.isEqual = function (other) {
  25285. if (this._keys.length !== other._keys.length) {
  25286. return false;
  25287. }
  25288. for (var index = 0; index < this._keys.length; index++) {
  25289. var prop = this._keys[index];
  25290. if (this[prop] !== other[prop]) {
  25291. return false;
  25292. }
  25293. }
  25294. return true;
  25295. };
  25296. MaterialDefines.prototype.cloneTo = function (other) {
  25297. if (this._keys.length !== other._keys.length) {
  25298. other._keys = this._keys.slice(0);
  25299. }
  25300. for (var index = 0; index < this._keys.length; index++) {
  25301. var prop = this._keys[index];
  25302. other[prop] = this[prop];
  25303. }
  25304. };
  25305. MaterialDefines.prototype.reset = function () {
  25306. for (var index = 0; index < this._keys.length; index++) {
  25307. var prop = this._keys[index];
  25308. if (typeof (this[prop]) === "number") {
  25309. this[prop] = 0;
  25310. }
  25311. else {
  25312. this[prop] = false;
  25313. }
  25314. }
  25315. };
  25316. MaterialDefines.prototype.toString = function () {
  25317. var result = "";
  25318. for (var index = 0; index < this._keys.length; index++) {
  25319. var prop = this._keys[index];
  25320. var value = this[prop];
  25321. if (typeof (value) === "number") {
  25322. result += "#define " + prop + " " + this[prop] + "\n";
  25323. }
  25324. else if (value) {
  25325. result += "#define " + prop + "\n";
  25326. }
  25327. }
  25328. return result;
  25329. };
  25330. return MaterialDefines;
  25331. }());
  25332. BABYLON.MaterialDefines = MaterialDefines;
  25333. var Material = (function () {
  25334. function Material(name, scene, doNotAdd) {
  25335. this.checkReadyOnEveryCall = false;
  25336. this.checkReadyOnlyOnce = false;
  25337. this.state = "";
  25338. this.alpha = 1.0;
  25339. this._backFaceCulling = true;
  25340. this.doNotSerialize = false;
  25341. this.storeEffectOnSubMeshes = false;
  25342. /**
  25343. * An event triggered when the material is disposed.
  25344. * @type {BABYLON.Observable}
  25345. */
  25346. this.onDisposeObservable = new BABYLON.Observable();
  25347. /**
  25348. * An event triggered when the material is bound.
  25349. * @type {BABYLON.Observable}
  25350. */
  25351. this.onBindObservable = new BABYLON.Observable();
  25352. /**
  25353. * An event triggered when the material is unbound.
  25354. * @type {BABYLON.Observable}
  25355. */
  25356. this.onUnBindObservable = new BABYLON.Observable();
  25357. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25358. this.disableDepthWrite = false;
  25359. this._fogEnabled = true;
  25360. this.pointSize = 1.0;
  25361. this.zOffset = 0;
  25362. this._wasPreviouslyReady = false;
  25363. this._fillMode = Material.TriangleFillMode;
  25364. this.name = name;
  25365. this.id = name || BABYLON.Tools.RandomId();
  25366. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25367. if (this._scene.useRightHandedSystem) {
  25368. this.sideOrientation = Material.ClockWiseSideOrientation;
  25369. }
  25370. else {
  25371. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25372. }
  25373. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25374. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  25375. if (!doNotAdd) {
  25376. this._scene.materials.push(this);
  25377. }
  25378. }
  25379. Object.defineProperty(Material, "TriangleFillMode", {
  25380. get: function () {
  25381. return Material._TriangleFillMode;
  25382. },
  25383. enumerable: true,
  25384. configurable: true
  25385. });
  25386. Object.defineProperty(Material, "WireFrameFillMode", {
  25387. get: function () {
  25388. return Material._WireFrameFillMode;
  25389. },
  25390. enumerable: true,
  25391. configurable: true
  25392. });
  25393. Object.defineProperty(Material, "PointFillMode", {
  25394. get: function () {
  25395. return Material._PointFillMode;
  25396. },
  25397. enumerable: true,
  25398. configurable: true
  25399. });
  25400. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25401. get: function () {
  25402. return Material._ClockWiseSideOrientation;
  25403. },
  25404. enumerable: true,
  25405. configurable: true
  25406. });
  25407. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25408. get: function () {
  25409. return Material._CounterClockWiseSideOrientation;
  25410. },
  25411. enumerable: true,
  25412. configurable: true
  25413. });
  25414. Object.defineProperty(Material, "TextureDirtyFlag", {
  25415. get: function () {
  25416. return Material._TextureDirtyFlag;
  25417. },
  25418. enumerable: true,
  25419. configurable: true
  25420. });
  25421. Object.defineProperty(Material, "LightDirtyFlag", {
  25422. get: function () {
  25423. return Material._LightDirtyFlag;
  25424. },
  25425. enumerable: true,
  25426. configurable: true
  25427. });
  25428. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25429. get: function () {
  25430. return Material._FresnelDirtyFlag;
  25431. },
  25432. enumerable: true,
  25433. configurable: true
  25434. });
  25435. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25436. get: function () {
  25437. return Material._AttributesDirtyFlag;
  25438. },
  25439. enumerable: true,
  25440. configurable: true
  25441. });
  25442. Object.defineProperty(Material, "MiscDirtyFlag", {
  25443. get: function () {
  25444. return Material._MiscDirtyFlag;
  25445. },
  25446. enumerable: true,
  25447. configurable: true
  25448. });
  25449. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25450. get: function () {
  25451. return this._backFaceCulling;
  25452. },
  25453. set: function (value) {
  25454. if (this._backFaceCulling === value) {
  25455. return;
  25456. }
  25457. this._backFaceCulling = value;
  25458. this.markAsDirty(Material.TextureDirtyFlag);
  25459. },
  25460. enumerable: true,
  25461. configurable: true
  25462. });
  25463. Object.defineProperty(Material.prototype, "onDispose", {
  25464. set: function (callback) {
  25465. if (this._onDisposeObserver) {
  25466. this.onDisposeObservable.remove(this._onDisposeObserver);
  25467. }
  25468. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25469. },
  25470. enumerable: true,
  25471. configurable: true
  25472. });
  25473. Object.defineProperty(Material.prototype, "onBind", {
  25474. set: function (callback) {
  25475. if (this._onBindObserver) {
  25476. this.onBindObservable.remove(this._onBindObserver);
  25477. }
  25478. this._onBindObserver = this.onBindObservable.add(callback);
  25479. },
  25480. enumerable: true,
  25481. configurable: true
  25482. });
  25483. Object.defineProperty(Material.prototype, "fogEnabled", {
  25484. get: function () {
  25485. return this._fogEnabled;
  25486. },
  25487. set: function (value) {
  25488. if (this._fogEnabled === value) {
  25489. return;
  25490. }
  25491. this._fogEnabled = value;
  25492. this.markAsDirty(Material.MiscDirtyFlag);
  25493. },
  25494. enumerable: true,
  25495. configurable: true
  25496. });
  25497. Object.defineProperty(Material.prototype, "wireframe", {
  25498. get: function () {
  25499. return this._fillMode === Material.WireFrameFillMode;
  25500. },
  25501. set: function (value) {
  25502. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25503. },
  25504. enumerable: true,
  25505. configurable: true
  25506. });
  25507. Object.defineProperty(Material.prototype, "pointsCloud", {
  25508. get: function () {
  25509. return this._fillMode === Material.PointFillMode;
  25510. },
  25511. set: function (value) {
  25512. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25513. },
  25514. enumerable: true,
  25515. configurable: true
  25516. });
  25517. Object.defineProperty(Material.prototype, "fillMode", {
  25518. get: function () {
  25519. return this._fillMode;
  25520. },
  25521. set: function (value) {
  25522. if (this._fillMode === value) {
  25523. return;
  25524. }
  25525. this._fillMode = value;
  25526. this.markAsDirty(Material.MiscDirtyFlag);
  25527. },
  25528. enumerable: true,
  25529. configurable: true
  25530. });
  25531. /**
  25532. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25533. * subclasses should override adding information pertainent to themselves
  25534. */
  25535. Material.prototype.toString = function (fullDetails) {
  25536. var ret = "Name: " + this.name;
  25537. if (fullDetails) {
  25538. }
  25539. return ret;
  25540. };
  25541. /**
  25542. * Child classes can use it to update shaders
  25543. */
  25544. Material.prototype.getClassName = function () {
  25545. return "Material";
  25546. };
  25547. Object.defineProperty(Material.prototype, "isFrozen", {
  25548. get: function () {
  25549. return this.checkReadyOnlyOnce;
  25550. },
  25551. enumerable: true,
  25552. configurable: true
  25553. });
  25554. Material.prototype.freeze = function () {
  25555. this.checkReadyOnlyOnce = true;
  25556. };
  25557. Material.prototype.unfreeze = function () {
  25558. this.checkReadyOnlyOnce = false;
  25559. };
  25560. Material.prototype.isReady = function (mesh, useInstances) {
  25561. return true;
  25562. };
  25563. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25564. return false;
  25565. };
  25566. Material.prototype.getEffect = function () {
  25567. return this._effect;
  25568. };
  25569. Material.prototype.getScene = function () {
  25570. return this._scene;
  25571. };
  25572. Material.prototype.needAlphaBlending = function () {
  25573. return (this.alpha < 1.0);
  25574. };
  25575. Material.prototype.needAlphaTesting = function () {
  25576. return false;
  25577. };
  25578. Material.prototype.getAlphaTestTexture = function () {
  25579. return null;
  25580. };
  25581. Material.prototype.markDirty = function () {
  25582. this._wasPreviouslyReady = false;
  25583. };
  25584. Material.prototype._preBind = function (effect) {
  25585. var engine = this._scene.getEngine();
  25586. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25587. engine.enableEffect(effect ? effect : this._effect);
  25588. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25589. };
  25590. Material.prototype.bind = function (world, mesh) {
  25591. };
  25592. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25593. };
  25594. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25595. };
  25596. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25597. sceneUbo.bindToEffect(effect, "Scene");
  25598. };
  25599. Material.prototype.bindView = function (effect) {
  25600. if (!this._useUBO) {
  25601. effect.setMatrix("view", this.getScene().getViewMatrix());
  25602. }
  25603. else {
  25604. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25605. }
  25606. };
  25607. Material.prototype.bindViewProjection = function (effect) {
  25608. if (!this._useUBO) {
  25609. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25610. }
  25611. else {
  25612. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25613. }
  25614. };
  25615. Material.prototype._afterBind = function (mesh) {
  25616. this._scene._cachedMaterial = this;
  25617. if (mesh) {
  25618. this._scene._cachedVisibility = mesh.visibility;
  25619. }
  25620. else {
  25621. this._scene._cachedVisibility = 1;
  25622. }
  25623. this.onBindObservable.notifyObservers(mesh);
  25624. if (this.disableDepthWrite) {
  25625. var engine = this._scene.getEngine();
  25626. this._cachedDepthWriteState = engine.getDepthWrite();
  25627. engine.setDepthWrite(false);
  25628. }
  25629. };
  25630. Material.prototype.unbind = function () {
  25631. this.onUnBindObservable.notifyObservers(this);
  25632. if (this.disableDepthWrite) {
  25633. var engine = this._scene.getEngine();
  25634. engine.setDepthWrite(this._cachedDepthWriteState);
  25635. }
  25636. };
  25637. Material.prototype.getActiveTextures = function () {
  25638. return [];
  25639. };
  25640. Material.prototype.hasTexture = function (texture) {
  25641. return false;
  25642. };
  25643. Material.prototype.clone = function (name) {
  25644. return null;
  25645. };
  25646. Material.prototype.getBindedMeshes = function () {
  25647. var result = new Array();
  25648. for (var index = 0; index < this._scene.meshes.length; index++) {
  25649. var mesh = this._scene.meshes[index];
  25650. if (mesh.material === this) {
  25651. result.push(mesh);
  25652. }
  25653. }
  25654. return result;
  25655. };
  25656. /**
  25657. * Force shader compilation including textures ready check
  25658. */
  25659. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25660. var _this = this;
  25661. var subMesh = new BABYLON.BaseSubMesh();
  25662. var scene = this.getScene();
  25663. var engine = scene.getEngine();
  25664. var checkReady = function () {
  25665. if (!_this._scene || !_this._scene.getEngine()) {
  25666. return;
  25667. }
  25668. if (subMesh._materialDefines) {
  25669. subMesh._materialDefines._renderId = -1;
  25670. }
  25671. var alphaTestState = engine.getAlphaTesting();
  25672. var clipPlaneState = scene.clipPlane;
  25673. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25674. if (options && options.clipPlane) {
  25675. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25676. }
  25677. if (_this.storeEffectOnSubMeshes) {
  25678. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25679. if (onCompiled) {
  25680. onCompiled(_this);
  25681. }
  25682. }
  25683. else {
  25684. setTimeout(checkReady, 16);
  25685. }
  25686. }
  25687. else {
  25688. if (_this.isReady(mesh)) {
  25689. if (onCompiled) {
  25690. onCompiled(_this);
  25691. }
  25692. }
  25693. else {
  25694. setTimeout(checkReady, 16);
  25695. }
  25696. }
  25697. engine.setAlphaTesting(alphaTestState);
  25698. if (options && options.clipPlane) {
  25699. scene.clipPlane = clipPlaneState;
  25700. }
  25701. };
  25702. checkReady();
  25703. };
  25704. Material.prototype.markAsDirty = function (flag) {
  25705. if (flag & Material.TextureDirtyFlag) {
  25706. this._markAllSubMeshesAsTexturesDirty();
  25707. }
  25708. if (flag & Material.LightDirtyFlag) {
  25709. this._markAllSubMeshesAsLightsDirty();
  25710. }
  25711. if (flag & Material.FresnelDirtyFlag) {
  25712. this._markAllSubMeshesAsFresnelDirty();
  25713. }
  25714. if (flag & Material.AttributesDirtyFlag) {
  25715. this._markAllSubMeshesAsAttributesDirty();
  25716. }
  25717. if (flag & Material.MiscDirtyFlag) {
  25718. this._markAllSubMeshesAsMiscDirty();
  25719. }
  25720. this.getScene().resetCachedMaterial();
  25721. };
  25722. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25723. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25724. var mesh = _a[_i];
  25725. if (!mesh.subMeshes) {
  25726. continue;
  25727. }
  25728. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25729. var subMesh = _c[_b];
  25730. if (subMesh.getMaterial() !== this) {
  25731. continue;
  25732. }
  25733. if (!subMesh._materialDefines) {
  25734. continue;
  25735. }
  25736. func(subMesh._materialDefines);
  25737. }
  25738. }
  25739. };
  25740. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25741. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25742. };
  25743. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25744. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25745. };
  25746. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25747. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25748. };
  25749. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25750. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25751. };
  25752. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  25753. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  25754. };
  25755. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  25756. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  25757. };
  25758. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25759. // Animations
  25760. this.getScene().stopAnimation(this);
  25761. // Remove from scene
  25762. var index = this._scene.materials.indexOf(this);
  25763. if (index >= 0) {
  25764. this._scene.materials.splice(index, 1);
  25765. }
  25766. // Remove from meshes
  25767. for (index = 0; index < this._scene.meshes.length; index++) {
  25768. var mesh = this._scene.meshes[index];
  25769. if (mesh.material === this) {
  25770. mesh.material = null;
  25771. if (mesh.geometry) {
  25772. var geometry = mesh.geometry;
  25773. if (this.storeEffectOnSubMeshes) {
  25774. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  25775. var subMesh = _a[_i];
  25776. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  25777. }
  25778. }
  25779. else {
  25780. geometry._releaseVertexArrayObject(this._effect);
  25781. }
  25782. }
  25783. }
  25784. }
  25785. this._uniformBuffer.dispose();
  25786. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25787. if (forceDisposeEffect && this._effect) {
  25788. if (this.storeEffectOnSubMeshes) {
  25789. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25790. var subMesh = _c[_b];
  25791. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  25792. }
  25793. }
  25794. else {
  25795. this._scene.getEngine()._releaseEffect(this._effect);
  25796. }
  25797. this._effect = null;
  25798. }
  25799. // Callback
  25800. this.onDisposeObservable.notifyObservers(this);
  25801. this.onDisposeObservable.clear();
  25802. this.onBindObservable.clear();
  25803. this.onUnBindObservable.clear();
  25804. };
  25805. Material.prototype.serialize = function () {
  25806. return BABYLON.SerializationHelper.Serialize(this);
  25807. };
  25808. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25809. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25810. multiMaterial.id = parsedMultiMaterial.id;
  25811. if (BABYLON.Tags) {
  25812. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25813. }
  25814. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25815. var subMatId = parsedMultiMaterial.materials[matIndex];
  25816. if (subMatId) {
  25817. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25818. }
  25819. else {
  25820. multiMaterial.subMaterials.push(null);
  25821. }
  25822. }
  25823. return multiMaterial;
  25824. };
  25825. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25826. if (!parsedMaterial.customType) {
  25827. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25828. }
  25829. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  25830. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  25831. if (!BABYLON.LegacyPBRMaterial) {
  25832. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  25833. return;
  25834. }
  25835. }
  25836. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25837. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25838. ;
  25839. };
  25840. Material._TriangleFillMode = 0;
  25841. Material._WireFrameFillMode = 1;
  25842. Material._PointFillMode = 2;
  25843. Material._ClockWiseSideOrientation = 0;
  25844. Material._CounterClockWiseSideOrientation = 1;
  25845. Material._TextureDirtyFlag = 1;
  25846. Material._LightDirtyFlag = 2;
  25847. Material._FresnelDirtyFlag = 4;
  25848. Material._AttributesDirtyFlag = 8;
  25849. Material._MiscDirtyFlag = 16;
  25850. __decorate([
  25851. BABYLON.serialize()
  25852. ], Material.prototype, "id", void 0);
  25853. __decorate([
  25854. BABYLON.serialize()
  25855. ], Material.prototype, "name", void 0);
  25856. __decorate([
  25857. BABYLON.serialize()
  25858. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25859. __decorate([
  25860. BABYLON.serialize()
  25861. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25862. __decorate([
  25863. BABYLON.serialize()
  25864. ], Material.prototype, "state", void 0);
  25865. __decorate([
  25866. BABYLON.serialize()
  25867. ], Material.prototype, "alpha", void 0);
  25868. __decorate([
  25869. BABYLON.serialize("backFaceCulling")
  25870. ], Material.prototype, "_backFaceCulling", void 0);
  25871. __decorate([
  25872. BABYLON.serialize()
  25873. ], Material.prototype, "sideOrientation", void 0);
  25874. __decorate([
  25875. BABYLON.serialize()
  25876. ], Material.prototype, "alphaMode", void 0);
  25877. __decorate([
  25878. BABYLON.serialize()
  25879. ], Material.prototype, "disableDepthWrite", void 0);
  25880. __decorate([
  25881. BABYLON.serialize("fogEnabled")
  25882. ], Material.prototype, "_fogEnabled", void 0);
  25883. __decorate([
  25884. BABYLON.serialize()
  25885. ], Material.prototype, "pointSize", void 0);
  25886. __decorate([
  25887. BABYLON.serialize()
  25888. ], Material.prototype, "zOffset", void 0);
  25889. __decorate([
  25890. BABYLON.serialize()
  25891. ], Material.prototype, "wireframe", null);
  25892. __decorate([
  25893. BABYLON.serialize()
  25894. ], Material.prototype, "pointsCloud", null);
  25895. __decorate([
  25896. BABYLON.serialize()
  25897. ], Material.prototype, "fillMode", null);
  25898. return Material;
  25899. }());
  25900. BABYLON.Material = Material;
  25901. })(BABYLON || (BABYLON = {}));
  25902. //# sourceMappingURL=babylon.material.js.map
  25903. var BABYLON;
  25904. (function (BABYLON) {
  25905. var UniformBuffer = (function () {
  25906. /**
  25907. * Uniform buffer objects.
  25908. *
  25909. * Handles blocks of uniform on the GPU.
  25910. *
  25911. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  25912. *
  25913. * For more information, please refer to :
  25914. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  25915. */
  25916. function UniformBuffer(engine, data, dynamic) {
  25917. this._engine = engine;
  25918. this._noUBO = !engine.supportsUniformBuffers;
  25919. this._dynamic = dynamic;
  25920. this._data = data || [];
  25921. this._uniformLocations = {};
  25922. this._uniformSizes = {};
  25923. this._uniformLocationPointer = 0;
  25924. this._needSync = false;
  25925. if (this._noUBO) {
  25926. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  25927. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  25928. this.updateFloat = this._updateFloatForEffect;
  25929. this.updateFloat2 = this._updateFloat2ForEffect;
  25930. this.updateFloat3 = this._updateFloat3ForEffect;
  25931. this.updateFloat4 = this._updateFloat4ForEffect;
  25932. this.updateMatrix = this._updateMatrixForEffect;
  25933. this.updateVector3 = this._updateVector3ForEffect;
  25934. this.updateVector4 = this._updateVector4ForEffect;
  25935. this.updateColor3 = this._updateColor3ForEffect;
  25936. this.updateColor4 = this._updateColor4ForEffect;
  25937. }
  25938. else {
  25939. this._engine._uniformBuffers.push(this);
  25940. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  25941. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  25942. this.updateFloat = this._updateFloatForUniform;
  25943. this.updateFloat2 = this._updateFloat2ForUniform;
  25944. this.updateFloat3 = this._updateFloat3ForUniform;
  25945. this.updateFloat4 = this._updateFloat4ForUniform;
  25946. this.updateMatrix = this._updateMatrixForUniform;
  25947. this.updateVector3 = this._updateVector3ForUniform;
  25948. this.updateVector4 = this._updateVector4ForUniform;
  25949. this.updateColor3 = this._updateColor3ForUniform;
  25950. this.updateColor4 = this._updateColor4ForUniform;
  25951. }
  25952. }
  25953. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  25954. // Properties
  25955. /**
  25956. * Indicates if the buffer is using the WebGL2 UBO implementation,
  25957. * or just falling back on setUniformXXX calls.
  25958. */
  25959. get: function () {
  25960. return !this._noUBO;
  25961. },
  25962. enumerable: true,
  25963. configurable: true
  25964. });
  25965. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  25966. /**
  25967. * Indicates if the WebGL underlying uniform buffer is in sync
  25968. * with the javascript cache data.
  25969. */
  25970. get: function () {
  25971. return !this._needSync;
  25972. },
  25973. enumerable: true,
  25974. configurable: true
  25975. });
  25976. /**
  25977. * Indicates if the WebGL underlying uniform buffer is dynamic.
  25978. * Also, a dynamic UniformBuffer will disable cache verification and always
  25979. * update the underlying WebGL uniform buffer to the GPU.
  25980. */
  25981. UniformBuffer.prototype.isDynamic = function () {
  25982. return this._dynamic;
  25983. };
  25984. /**
  25985. * The data cache on JS side.
  25986. */
  25987. UniformBuffer.prototype.getData = function () {
  25988. return this._bufferData;
  25989. };
  25990. /**
  25991. * The underlying WebGL Uniform buffer.
  25992. */
  25993. UniformBuffer.prototype.getBuffer = function () {
  25994. return this._buffer;
  25995. };
  25996. /**
  25997. * std140 layout specifies how to align data within an UBO structure.
  25998. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  25999. * for specs.
  26000. */
  26001. UniformBuffer.prototype._fillAlignment = function (size) {
  26002. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  26003. // and 4x4 matrices
  26004. // TODO : change if other types are used
  26005. var alignment;
  26006. if (size <= 2) {
  26007. alignment = size;
  26008. }
  26009. else {
  26010. alignment = 4;
  26011. }
  26012. if ((this._uniformLocationPointer % alignment) !== 0) {
  26013. var oldPointer = this._uniformLocationPointer;
  26014. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  26015. var diff = this._uniformLocationPointer - oldPointer;
  26016. for (var i = 0; i < diff; i++) {
  26017. this._data.push(0);
  26018. }
  26019. }
  26020. };
  26021. /**
  26022. * Adds an uniform in the buffer.
  26023. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  26024. * for the layout to be correct !
  26025. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26026. * @param {number|number[]} size Data size, or data directly.
  26027. */
  26028. UniformBuffer.prototype.addUniform = function (name, size) {
  26029. if (this._noUBO) {
  26030. return;
  26031. }
  26032. if (this._uniformLocations[name] !== undefined) {
  26033. // Already existing uniform
  26034. return;
  26035. }
  26036. // This function must be called in the order of the shader layout !
  26037. // size can be the size of the uniform, or data directly
  26038. var data;
  26039. if (size instanceof Array) {
  26040. data = size;
  26041. size = data.length;
  26042. }
  26043. else {
  26044. size = size;
  26045. data = [];
  26046. // Fill with zeros
  26047. for (var i = 0; i < size; i++) {
  26048. data.push(0);
  26049. }
  26050. }
  26051. this._fillAlignment(size);
  26052. this._uniformSizes[name] = size;
  26053. this._uniformLocations[name] = this._uniformLocationPointer;
  26054. this._uniformLocationPointer += size;
  26055. for (var i = 0; i < size; i++) {
  26056. this._data.push(data[i]);
  26057. }
  26058. this._needSync = true;
  26059. };
  26060. /**
  26061. * Wrapper for addUniform.
  26062. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26063. * @param {Matrix} mat A 4x4 matrix.
  26064. */
  26065. UniformBuffer.prototype.addMatrix = function (name, mat) {
  26066. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  26067. };
  26068. /**
  26069. * Wrapper for addUniform.
  26070. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26071. * @param {number} x
  26072. * @param {number} y
  26073. */
  26074. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  26075. var temp = [x, y];
  26076. this.addUniform(name, temp);
  26077. };
  26078. /**
  26079. * Wrapper for addUniform.
  26080. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26081. * @param {number} x
  26082. * @param {number} y
  26083. * @param {number} z
  26084. */
  26085. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  26086. var temp = [x, y, z];
  26087. this.addUniform(name, temp);
  26088. };
  26089. /**
  26090. * Wrapper for addUniform.
  26091. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26092. * @param {Color3} color
  26093. */
  26094. UniformBuffer.prototype.addColor3 = function (name, color) {
  26095. var temp = [];
  26096. color.toArray(temp);
  26097. this.addUniform(name, temp);
  26098. };
  26099. /**
  26100. * Wrapper for addUniform.
  26101. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26102. * @param {Color3} color
  26103. * @param {number} alpha
  26104. */
  26105. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  26106. var temp = [];
  26107. color.toArray(temp);
  26108. temp.push(alpha);
  26109. this.addUniform(name, temp);
  26110. };
  26111. /**
  26112. * Wrapper for addUniform.
  26113. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26114. * @param {Vector3} vector
  26115. */
  26116. UniformBuffer.prototype.addVector3 = function (name, vector) {
  26117. var temp = [];
  26118. vector.toArray(temp);
  26119. this.addUniform(name, temp);
  26120. };
  26121. /**
  26122. * Wrapper for addUniform.
  26123. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26124. */
  26125. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  26126. this.addUniform(name, 12);
  26127. };
  26128. /**
  26129. * Wrapper for addUniform.
  26130. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26131. */
  26132. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  26133. this.addUniform(name, 8);
  26134. };
  26135. /**
  26136. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  26137. */
  26138. UniformBuffer.prototype.create = function () {
  26139. if (this._noUBO) {
  26140. return;
  26141. }
  26142. if (this._buffer) {
  26143. return; // nothing to do
  26144. }
  26145. // See spec, alignment must be filled as a vec4
  26146. this._fillAlignment(4);
  26147. this._bufferData = new Float32Array(this._data);
  26148. this._rebuild();
  26149. this._needSync = true;
  26150. };
  26151. UniformBuffer.prototype._rebuild = function () {
  26152. if (this._noUBO) {
  26153. return;
  26154. }
  26155. if (this._dynamic) {
  26156. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  26157. }
  26158. else {
  26159. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  26160. }
  26161. };
  26162. /**
  26163. * Updates the WebGL Uniform Buffer on the GPU.
  26164. * If the `dynamic` flag is set to true, no cache comparison is done.
  26165. * Otherwise, the buffer will be updated only if the cache differs.
  26166. */
  26167. UniformBuffer.prototype.update = function () {
  26168. if (!this._buffer) {
  26169. this.create();
  26170. return;
  26171. }
  26172. if (!this._dynamic && !this._needSync) {
  26173. return;
  26174. }
  26175. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  26176. this._needSync = false;
  26177. };
  26178. /**
  26179. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26180. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26181. * @param {number[]|Float32Array} data Flattened data
  26182. * @param {number} size Size of the data.
  26183. */
  26184. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26185. var location = this._uniformLocations[uniformName];
  26186. if (location === undefined) {
  26187. if (this._buffer) {
  26188. // Cannot add an uniform if the buffer is already created
  26189. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26190. return;
  26191. }
  26192. this.addUniform(uniformName, size);
  26193. location = this._uniformLocations[uniformName];
  26194. }
  26195. if (!this._buffer) {
  26196. this.create();
  26197. }
  26198. if (!this._dynamic) {
  26199. // Cache for static uniform buffers
  26200. var changed = false;
  26201. for (var i = 0; i < size; i++) {
  26202. if (this._bufferData[location + i] !== data[i]) {
  26203. changed = true;
  26204. this._bufferData[location + i] = data[i];
  26205. }
  26206. }
  26207. this._needSync = this._needSync || changed;
  26208. }
  26209. else {
  26210. // No cache for dynamic
  26211. for (var i = 0; i < size; i++) {
  26212. this._bufferData[location + i] = data[i];
  26213. }
  26214. }
  26215. };
  26216. // Update methods
  26217. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26218. // To match std140, matrix must be realigned
  26219. for (var i = 0; i < 3; i++) {
  26220. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26221. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26222. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26223. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26224. }
  26225. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26226. };
  26227. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26228. this._currentEffect.setMatrix3x3(name, matrix);
  26229. };
  26230. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26231. this._currentEffect.setMatrix2x2(name, matrix);
  26232. };
  26233. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26234. // To match std140, matrix must be realigned
  26235. for (var i = 0; i < 2; i++) {
  26236. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26237. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26238. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26239. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26240. }
  26241. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26242. };
  26243. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26244. this._currentEffect.setFloat(name, x);
  26245. };
  26246. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26247. UniformBuffer._tempBuffer[0] = x;
  26248. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26249. };
  26250. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26251. if (suffix === void 0) { suffix = ""; }
  26252. this._currentEffect.setFloat2(name + suffix, x, y);
  26253. };
  26254. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26255. if (suffix === void 0) { suffix = ""; }
  26256. UniformBuffer._tempBuffer[0] = x;
  26257. UniformBuffer._tempBuffer[1] = y;
  26258. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26259. };
  26260. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26261. if (suffix === void 0) { suffix = ""; }
  26262. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26263. };
  26264. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26265. if (suffix === void 0) { suffix = ""; }
  26266. UniformBuffer._tempBuffer[0] = x;
  26267. UniformBuffer._tempBuffer[1] = y;
  26268. UniformBuffer._tempBuffer[2] = z;
  26269. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26270. };
  26271. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26272. if (suffix === void 0) { suffix = ""; }
  26273. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26274. };
  26275. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26276. if (suffix === void 0) { suffix = ""; }
  26277. UniformBuffer._tempBuffer[0] = x;
  26278. UniformBuffer._tempBuffer[1] = y;
  26279. UniformBuffer._tempBuffer[2] = z;
  26280. UniformBuffer._tempBuffer[3] = w;
  26281. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26282. };
  26283. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26284. this._currentEffect.setMatrix(name, mat);
  26285. };
  26286. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26287. this.updateUniform(name, mat.toArray(), 16);
  26288. };
  26289. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26290. this._currentEffect.setVector3(name, vector);
  26291. };
  26292. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26293. vector.toArray(UniformBuffer._tempBuffer);
  26294. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26295. };
  26296. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26297. this._currentEffect.setVector4(name, vector);
  26298. };
  26299. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26300. vector.toArray(UniformBuffer._tempBuffer);
  26301. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26302. };
  26303. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26304. if (suffix === void 0) { suffix = ""; }
  26305. this._currentEffect.setColor3(name + suffix, color);
  26306. };
  26307. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26308. if (suffix === void 0) { suffix = ""; }
  26309. color.toArray(UniformBuffer._tempBuffer);
  26310. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26311. };
  26312. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26313. if (suffix === void 0) { suffix = ""; }
  26314. this._currentEffect.setColor4(name + suffix, color, alpha);
  26315. };
  26316. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26317. if (suffix === void 0) { suffix = ""; }
  26318. color.toArray(UniformBuffer._tempBuffer);
  26319. UniformBuffer._tempBuffer[3] = alpha;
  26320. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26321. };
  26322. /**
  26323. * Sets a sampler uniform on the effect.
  26324. * @param {string} name Name of the sampler.
  26325. * @param {Texture} texture
  26326. */
  26327. UniformBuffer.prototype.setTexture = function (name, texture) {
  26328. this._currentEffect.setTexture(name, texture);
  26329. };
  26330. /**
  26331. * Directly updates the value of the uniform in the cache AND on the GPU.
  26332. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26333. * @param {number[]|Float32Array} data Flattened data
  26334. */
  26335. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26336. this.updateUniform(uniformName, data, data.length);
  26337. this.update();
  26338. };
  26339. /**
  26340. * Binds this uniform buffer to an effect.
  26341. * @param {Effect} effect
  26342. * @param {string} name Name of the uniform block in the shader.
  26343. */
  26344. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26345. this._currentEffect = effect;
  26346. if (this._noUBO) {
  26347. return;
  26348. }
  26349. effect.bindUniformBuffer(this._buffer, name);
  26350. };
  26351. /**
  26352. * Disposes the uniform buffer.
  26353. */
  26354. UniformBuffer.prototype.dispose = function () {
  26355. if (this._noUBO) {
  26356. return;
  26357. }
  26358. var index = this._engine._uniformBuffers.indexOf(this);
  26359. if (index !== -1) {
  26360. this._engine._uniformBuffers.splice(index, 1);
  26361. }
  26362. if (!this._buffer) {
  26363. return;
  26364. }
  26365. if (this._engine._releaseBuffer(this._buffer)) {
  26366. this._buffer = null;
  26367. }
  26368. };
  26369. // Pool for avoiding memory leaks
  26370. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26371. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26372. return UniformBuffer;
  26373. }());
  26374. BABYLON.UniformBuffer = UniformBuffer;
  26375. })(BABYLON || (BABYLON = {}));
  26376. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26377. var BABYLON;
  26378. (function (BABYLON) {
  26379. var PushMaterial = (function (_super) {
  26380. __extends(PushMaterial, _super);
  26381. function PushMaterial(name, scene) {
  26382. var _this = _super.call(this, name, scene) || this;
  26383. _this.storeEffectOnSubMeshes = true;
  26384. return _this;
  26385. }
  26386. PushMaterial.prototype.getEffect = function () {
  26387. return this._activeEffect;
  26388. };
  26389. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26390. if (!mesh) {
  26391. return false;
  26392. }
  26393. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26394. return true;
  26395. }
  26396. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26397. };
  26398. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26399. this._activeEffect.setMatrix("world", world);
  26400. };
  26401. PushMaterial.prototype.bind = function (world, mesh) {
  26402. if (!mesh) {
  26403. return;
  26404. }
  26405. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26406. };
  26407. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26408. _super.prototype._afterBind.call(this, mesh);
  26409. this.getScene()._cachedEffect = effect;
  26410. };
  26411. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26412. if (visibility === void 0) { visibility = 1; }
  26413. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26414. };
  26415. return PushMaterial;
  26416. }(BABYLON.Material));
  26417. BABYLON.PushMaterial = PushMaterial;
  26418. })(BABYLON || (BABYLON = {}));
  26419. //# sourceMappingURL=babylon.pushMaterial.js.map
  26420. var BABYLON;
  26421. (function (BABYLON) {
  26422. var VertexData = (function () {
  26423. function VertexData() {
  26424. }
  26425. VertexData.prototype.set = function (data, kind) {
  26426. switch (kind) {
  26427. case BABYLON.VertexBuffer.PositionKind:
  26428. this.positions = data;
  26429. break;
  26430. case BABYLON.VertexBuffer.NormalKind:
  26431. this.normals = data;
  26432. break;
  26433. case BABYLON.VertexBuffer.TangentKind:
  26434. this.tangents = data;
  26435. break;
  26436. case BABYLON.VertexBuffer.UVKind:
  26437. this.uvs = data;
  26438. break;
  26439. case BABYLON.VertexBuffer.UV2Kind:
  26440. this.uvs2 = data;
  26441. break;
  26442. case BABYLON.VertexBuffer.UV3Kind:
  26443. this.uvs3 = data;
  26444. break;
  26445. case BABYLON.VertexBuffer.UV4Kind:
  26446. this.uvs4 = data;
  26447. break;
  26448. case BABYLON.VertexBuffer.UV5Kind:
  26449. this.uvs5 = data;
  26450. break;
  26451. case BABYLON.VertexBuffer.UV6Kind:
  26452. this.uvs6 = data;
  26453. break;
  26454. case BABYLON.VertexBuffer.ColorKind:
  26455. this.colors = data;
  26456. break;
  26457. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26458. this.matricesIndices = data;
  26459. break;
  26460. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26461. this.matricesWeights = data;
  26462. break;
  26463. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26464. this.matricesIndicesExtra = data;
  26465. break;
  26466. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26467. this.matricesWeightsExtra = data;
  26468. break;
  26469. }
  26470. };
  26471. /**
  26472. * Associates the vertexData to the passed Mesh.
  26473. * Sets it as updatable or not (default `false`).
  26474. * Returns the VertexData.
  26475. */
  26476. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26477. this._applyTo(mesh, updatable);
  26478. return this;
  26479. };
  26480. /**
  26481. * Associates the vertexData to the passed Geometry.
  26482. * Sets it as updatable or not (default `false`).
  26483. * Returns the VertexData.
  26484. */
  26485. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26486. this._applyTo(geometry, updatable);
  26487. return this;
  26488. };
  26489. /**
  26490. * Updates the associated mesh.
  26491. * Returns the VertexData.
  26492. */
  26493. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26494. this._update(mesh);
  26495. return this;
  26496. };
  26497. /**
  26498. * Updates the associated geometry.
  26499. * Returns the VertexData.
  26500. */
  26501. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26502. this._update(geometry);
  26503. return this;
  26504. };
  26505. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26506. if (this.positions) {
  26507. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26508. }
  26509. if (this.normals) {
  26510. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26511. }
  26512. if (this.tangents) {
  26513. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26514. }
  26515. if (this.uvs) {
  26516. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26517. }
  26518. if (this.uvs2) {
  26519. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26520. }
  26521. if (this.uvs3) {
  26522. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26523. }
  26524. if (this.uvs4) {
  26525. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26526. }
  26527. if (this.uvs5) {
  26528. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26529. }
  26530. if (this.uvs6) {
  26531. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26532. }
  26533. if (this.colors) {
  26534. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26535. }
  26536. if (this.matricesIndices) {
  26537. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26538. }
  26539. if (this.matricesWeights) {
  26540. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26541. }
  26542. if (this.matricesIndicesExtra) {
  26543. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26544. }
  26545. if (this.matricesWeightsExtra) {
  26546. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26547. }
  26548. if (this.indices) {
  26549. meshOrGeometry.setIndices(this.indices);
  26550. }
  26551. return this;
  26552. };
  26553. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26554. if (this.positions) {
  26555. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26556. }
  26557. if (this.normals) {
  26558. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26559. }
  26560. if (this.tangents) {
  26561. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26562. }
  26563. if (this.uvs) {
  26564. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26565. }
  26566. if (this.uvs2) {
  26567. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26568. }
  26569. if (this.uvs3) {
  26570. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26571. }
  26572. if (this.uvs4) {
  26573. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26574. }
  26575. if (this.uvs5) {
  26576. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26577. }
  26578. if (this.uvs6) {
  26579. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26580. }
  26581. if (this.colors) {
  26582. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26583. }
  26584. if (this.matricesIndices) {
  26585. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26586. }
  26587. if (this.matricesWeights) {
  26588. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26589. }
  26590. if (this.matricesIndicesExtra) {
  26591. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26592. }
  26593. if (this.matricesWeightsExtra) {
  26594. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26595. }
  26596. if (this.indices) {
  26597. meshOrGeometry.setIndices(this.indices);
  26598. }
  26599. return this;
  26600. };
  26601. /**
  26602. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26603. * Returns the VertexData.
  26604. */
  26605. VertexData.prototype.transform = function (matrix) {
  26606. var transformed = BABYLON.Vector3.Zero();
  26607. var index;
  26608. if (this.positions) {
  26609. var position = BABYLON.Vector3.Zero();
  26610. for (index = 0; index < this.positions.length; index += 3) {
  26611. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26612. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26613. this.positions[index] = transformed.x;
  26614. this.positions[index + 1] = transformed.y;
  26615. this.positions[index + 2] = transformed.z;
  26616. }
  26617. }
  26618. if (this.normals) {
  26619. var normal = BABYLON.Vector3.Zero();
  26620. for (index = 0; index < this.normals.length; index += 3) {
  26621. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26622. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26623. this.normals[index] = transformed.x;
  26624. this.normals[index + 1] = transformed.y;
  26625. this.normals[index + 2] = transformed.z;
  26626. }
  26627. }
  26628. if (this.tangents) {
  26629. var tangent = BABYLON.Vector4.Zero();
  26630. var tangentTransformed = BABYLON.Vector4.Zero();
  26631. for (index = 0; index < this.tangents.length; index += 4) {
  26632. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26633. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26634. this.tangents[index] = tangentTransformed.x;
  26635. this.tangents[index + 1] = tangentTransformed.y;
  26636. this.tangents[index + 2] = tangentTransformed.z;
  26637. this.tangents[index + 3] = tangentTransformed.w;
  26638. }
  26639. }
  26640. return this;
  26641. };
  26642. /**
  26643. * Merges the passed VertexData into the current one.
  26644. * Returns the modified VertexData.
  26645. */
  26646. VertexData.prototype.merge = function (other) {
  26647. if (other.indices) {
  26648. if (!this.indices) {
  26649. this.indices = [];
  26650. }
  26651. var offset = this.positions ? this.positions.length / 3 : 0;
  26652. for (var index = 0; index < other.indices.length; index++) {
  26653. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26654. this.indices.push(other.indices[index] + offset);
  26655. }
  26656. }
  26657. this.positions = this._mergeElement(this.positions, other.positions);
  26658. this.normals = this._mergeElement(this.normals, other.normals);
  26659. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26660. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26661. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26662. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26663. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26664. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26665. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26666. this.colors = this._mergeElement(this.colors, other.colors);
  26667. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26668. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26669. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26670. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26671. return this;
  26672. };
  26673. VertexData.prototype._mergeElement = function (source, other) {
  26674. if (!other)
  26675. return source;
  26676. if (!source)
  26677. return other;
  26678. var len = other.length + source.length;
  26679. var isSrcTypedArray = source instanceof Float32Array;
  26680. var isOthTypedArray = other instanceof Float32Array;
  26681. // use non-loop method when the source is Float32Array
  26682. if (isSrcTypedArray) {
  26683. var ret32 = new Float32Array(len);
  26684. ret32.set(source);
  26685. ret32.set(other, source.length);
  26686. return ret32;
  26687. // source is number[], when other is also use concat
  26688. }
  26689. else if (!isOthTypedArray) {
  26690. return source.concat(other);
  26691. // source is a number[], but other is a Float32Array, loop required
  26692. }
  26693. else {
  26694. var ret = source.slice(0); // copy source to a separate array
  26695. for (var i = 0, len = other.length; i < len; i++) {
  26696. ret.push(other[i]);
  26697. }
  26698. return ret;
  26699. }
  26700. };
  26701. /**
  26702. * Serializes the VertexData.
  26703. * Returns a serialized object.
  26704. */
  26705. VertexData.prototype.serialize = function () {
  26706. var serializationObject = this.serialize();
  26707. if (this.positions) {
  26708. serializationObject.positions = this.positions;
  26709. }
  26710. if (this.normals) {
  26711. serializationObject.normals = this.normals;
  26712. }
  26713. if (this.tangents) {
  26714. serializationObject.tangents = this.tangents;
  26715. }
  26716. if (this.uvs) {
  26717. serializationObject.uvs = this.uvs;
  26718. }
  26719. if (this.uvs2) {
  26720. serializationObject.uvs2 = this.uvs2;
  26721. }
  26722. if (this.uvs3) {
  26723. serializationObject.uvs3 = this.uvs3;
  26724. }
  26725. if (this.uvs4) {
  26726. serializationObject.uvs4 = this.uvs4;
  26727. }
  26728. if (this.uvs5) {
  26729. serializationObject.uvs5 = this.uvs5;
  26730. }
  26731. if (this.uvs6) {
  26732. serializationObject.uvs6 = this.uvs6;
  26733. }
  26734. if (this.colors) {
  26735. serializationObject.colors = this.colors;
  26736. }
  26737. if (this.matricesIndices) {
  26738. serializationObject.matricesIndices = this.matricesIndices;
  26739. serializationObject.matricesIndices._isExpanded = true;
  26740. }
  26741. if (this.matricesWeights) {
  26742. serializationObject.matricesWeights = this.matricesWeights;
  26743. }
  26744. if (this.matricesIndicesExtra) {
  26745. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26746. serializationObject.matricesIndicesExtra._isExpanded = true;
  26747. }
  26748. if (this.matricesWeightsExtra) {
  26749. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26750. }
  26751. serializationObject.indices = this.indices;
  26752. return serializationObject;
  26753. };
  26754. // Statics
  26755. /**
  26756. * Returns the object VertexData associated to the passed mesh.
  26757. */
  26758. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  26759. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  26760. };
  26761. /**
  26762. * Returns the object VertexData associated to the passed geometry.
  26763. */
  26764. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  26765. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  26766. };
  26767. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  26768. var result = new VertexData();
  26769. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26770. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  26771. }
  26772. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26773. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  26774. }
  26775. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26776. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  26777. }
  26778. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26779. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  26780. }
  26781. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26782. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  26783. }
  26784. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26785. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  26786. }
  26787. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26788. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  26789. }
  26790. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26791. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  26792. }
  26793. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26794. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  26795. }
  26796. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26797. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  26798. }
  26799. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26800. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  26801. }
  26802. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26803. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  26804. }
  26805. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26806. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  26807. }
  26808. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26809. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  26810. }
  26811. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26812. return result;
  26813. };
  26814. /**
  26815. * Creates the vertexData of the Ribbon.
  26816. */
  26817. VertexData.CreateRibbon = function (options) {
  26818. var pathArray = options.pathArray;
  26819. var closeArray = options.closeArray || false;
  26820. var closePath = options.closePath || false;
  26821. var invertUV = options.invertUV || false;
  26822. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26823. var offset = options.offset || defaultOffset;
  26824. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26825. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26826. var customUV = options.uvs;
  26827. var customColors = options.colors;
  26828. var positions = [];
  26829. var indices = [];
  26830. var normals = [];
  26831. var uvs = [];
  26832. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26833. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26834. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26835. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26836. var minlg; // minimal length among all paths from pathArray
  26837. var lg = []; // array of path lengths : nb of vertex per path
  26838. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26839. var p; // path iterator
  26840. var i; // point iterator
  26841. var j; // point iterator
  26842. // if single path in pathArray
  26843. if (pathArray.length < 2) {
  26844. var ar1 = [];
  26845. var ar2 = [];
  26846. for (i = 0; i < pathArray[0].length - offset; i++) {
  26847. ar1.push(pathArray[0][i]);
  26848. ar2.push(pathArray[0][i + offset]);
  26849. }
  26850. pathArray = [ar1, ar2];
  26851. }
  26852. // positions and horizontal distances (u)
  26853. var idc = 0;
  26854. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  26855. var path;
  26856. var l;
  26857. minlg = pathArray[0].length;
  26858. var vectlg;
  26859. var dist;
  26860. for (p = 0; p < pathArray.length; p++) {
  26861. uTotalDistance[p] = 0;
  26862. us[p] = [0];
  26863. path = pathArray[p];
  26864. l = path.length;
  26865. minlg = (minlg < l) ? minlg : l;
  26866. j = 0;
  26867. while (j < l) {
  26868. positions.push(path[j].x, path[j].y, path[j].z);
  26869. if (j > 0) {
  26870. vectlg = path[j].subtract(path[j - 1]).length();
  26871. dist = vectlg + uTotalDistance[p];
  26872. us[p].push(dist);
  26873. uTotalDistance[p] = dist;
  26874. }
  26875. j++;
  26876. }
  26877. if (closePath) {
  26878. j--;
  26879. positions.push(path[0].x, path[0].y, path[0].z);
  26880. vectlg = path[j].subtract(path[0]).length();
  26881. dist = vectlg + uTotalDistance[p];
  26882. us[p].push(dist);
  26883. uTotalDistance[p] = dist;
  26884. }
  26885. lg[p] = l + closePathCorr;
  26886. idx[p] = idc;
  26887. idc += (l + closePathCorr);
  26888. }
  26889. // vertical distances (v)
  26890. var path1;
  26891. var path2;
  26892. var vertex1;
  26893. var vertex2;
  26894. for (i = 0; i < minlg + closePathCorr; i++) {
  26895. vTotalDistance[i] = 0;
  26896. vs[i] = [0];
  26897. for (p = 0; p < pathArray.length - 1; p++) {
  26898. path1 = pathArray[p];
  26899. path2 = pathArray[p + 1];
  26900. if (i === minlg) {
  26901. vertex1 = path1[0];
  26902. vertex2 = path2[0];
  26903. }
  26904. else {
  26905. vertex1 = path1[i];
  26906. vertex2 = path2[i];
  26907. }
  26908. vectlg = vertex2.subtract(vertex1).length();
  26909. dist = vectlg + vTotalDistance[i];
  26910. vs[i].push(dist);
  26911. vTotalDistance[i] = dist;
  26912. }
  26913. if (closeArray) {
  26914. path1 = pathArray[p];
  26915. path2 = pathArray[0];
  26916. if (i === minlg) {
  26917. vertex2 = path2[0];
  26918. }
  26919. vectlg = vertex2.subtract(vertex1).length();
  26920. dist = vectlg + vTotalDistance[i];
  26921. vTotalDistance[i] = dist;
  26922. }
  26923. }
  26924. // uvs
  26925. var u;
  26926. var v;
  26927. if (customUV) {
  26928. for (p = 0; p < customUV.length; p++) {
  26929. uvs.push(customUV[p].x, customUV[p].y);
  26930. }
  26931. }
  26932. else {
  26933. for (p = 0; p < pathArray.length; p++) {
  26934. for (i = 0; i < minlg + closePathCorr; i++) {
  26935. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  26936. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  26937. if (invertUV) {
  26938. uvs.push(v, u);
  26939. }
  26940. else {
  26941. uvs.push(u, v);
  26942. }
  26943. }
  26944. }
  26945. }
  26946. // indices
  26947. p = 0; // path index
  26948. var pi = 0; // positions array index
  26949. var l1 = lg[p] - 1; // path1 length
  26950. var l2 = lg[p + 1] - 1; // path2 length
  26951. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26952. var shft = idx[1] - idx[0]; // shift
  26953. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26954. while (pi <= min && p < path1nb) {
  26955. // 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
  26956. indices.push(pi, pi + shft, pi + 1);
  26957. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26958. pi += 1;
  26959. if (pi === min) {
  26960. p++;
  26961. if (p === lg.length - 1) {
  26962. shft = idx[0] - idx[p];
  26963. l1 = lg[p] - 1;
  26964. l2 = lg[0] - 1;
  26965. }
  26966. else {
  26967. shft = idx[p + 1] - idx[p];
  26968. l1 = lg[p] - 1;
  26969. l2 = lg[p + 1] - 1;
  26970. }
  26971. pi = idx[p];
  26972. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26973. }
  26974. }
  26975. // normals
  26976. VertexData.ComputeNormals(positions, indices, normals);
  26977. if (closePath) {
  26978. var indexFirst = 0;
  26979. var indexLast = 0;
  26980. for (p = 0; p < pathArray.length; p++) {
  26981. indexFirst = idx[p] * 3;
  26982. if (p + 1 < pathArray.length) {
  26983. indexLast = (idx[p + 1] - 1) * 3;
  26984. }
  26985. else {
  26986. indexLast = normals.length - 3;
  26987. }
  26988. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26989. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26990. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26991. normals[indexLast] = normals[indexFirst];
  26992. normals[indexLast + 1] = normals[indexFirst + 1];
  26993. normals[indexLast + 2] = normals[indexFirst + 2];
  26994. }
  26995. }
  26996. // sides
  26997. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26998. // Colors
  26999. if (customColors) {
  27000. var colors = new Float32Array(customColors.length * 4);
  27001. for (var c = 0; c < customColors.length; c++) {
  27002. colors[c * 4] = customColors[c].r;
  27003. colors[c * 4 + 1] = customColors[c].g;
  27004. colors[c * 4 + 2] = customColors[c].b;
  27005. colors[c * 4 + 3] = customColors[c].a;
  27006. }
  27007. }
  27008. // Result
  27009. var vertexData = new VertexData();
  27010. var positions32 = new Float32Array(positions);
  27011. var normals32 = new Float32Array(normals);
  27012. var uvs32 = new Float32Array(uvs);
  27013. vertexData.indices = indices;
  27014. vertexData.positions = positions32;
  27015. vertexData.normals = normals32;
  27016. vertexData.uvs = uvs32;
  27017. if (customColors) {
  27018. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  27019. }
  27020. if (closePath) {
  27021. vertexData._idx = idx;
  27022. }
  27023. return vertexData;
  27024. };
  27025. /**
  27026. * Creates the VertexData of the Box.
  27027. */
  27028. VertexData.CreateBox = function (options) {
  27029. var normalsSource = [
  27030. new BABYLON.Vector3(0, 0, 1),
  27031. new BABYLON.Vector3(0, 0, -1),
  27032. new BABYLON.Vector3(1, 0, 0),
  27033. new BABYLON.Vector3(-1, 0, 0),
  27034. new BABYLON.Vector3(0, 1, 0),
  27035. new BABYLON.Vector3(0, -1, 0)
  27036. ];
  27037. var indices = [];
  27038. var positions = [];
  27039. var normals = [];
  27040. var uvs = [];
  27041. var width = options.width || options.size || 1;
  27042. var height = options.height || options.size || 1;
  27043. var depth = options.depth || options.size || 1;
  27044. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27045. var faceUV = options.faceUV || new Array(6);
  27046. var faceColors = options.faceColors;
  27047. var colors = [];
  27048. // default face colors and UV if undefined
  27049. for (var f = 0; f < 6; f++) {
  27050. if (faceUV[f] === undefined) {
  27051. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27052. }
  27053. if (faceColors && faceColors[f] === undefined) {
  27054. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27055. }
  27056. }
  27057. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27058. // Create each face in turn.
  27059. for (var index = 0; index < normalsSource.length; index++) {
  27060. var normal = normalsSource[index];
  27061. // Get two vectors perpendicular to the face normal and to each other.
  27062. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27063. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27064. // Six indices (two triangles) per face.
  27065. var verticesLength = positions.length / 3;
  27066. indices.push(verticesLength);
  27067. indices.push(verticesLength + 1);
  27068. indices.push(verticesLength + 2);
  27069. indices.push(verticesLength);
  27070. indices.push(verticesLength + 2);
  27071. indices.push(verticesLength + 3);
  27072. // Four vertices per face.
  27073. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27074. positions.push(vertex.x, vertex.y, vertex.z);
  27075. normals.push(normal.x, normal.y, normal.z);
  27076. uvs.push(faceUV[index].z, faceUV[index].w);
  27077. if (faceColors) {
  27078. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27079. }
  27080. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27081. positions.push(vertex.x, vertex.y, vertex.z);
  27082. normals.push(normal.x, normal.y, normal.z);
  27083. uvs.push(faceUV[index].x, faceUV[index].w);
  27084. if (faceColors) {
  27085. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27086. }
  27087. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27088. positions.push(vertex.x, vertex.y, vertex.z);
  27089. normals.push(normal.x, normal.y, normal.z);
  27090. uvs.push(faceUV[index].x, faceUV[index].y);
  27091. if (faceColors) {
  27092. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27093. }
  27094. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27095. positions.push(vertex.x, vertex.y, vertex.z);
  27096. normals.push(normal.x, normal.y, normal.z);
  27097. uvs.push(faceUV[index].z, faceUV[index].y);
  27098. if (faceColors) {
  27099. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27100. }
  27101. }
  27102. // sides
  27103. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27104. // Result
  27105. var vertexData = new VertexData();
  27106. vertexData.indices = indices;
  27107. vertexData.positions = positions;
  27108. vertexData.normals = normals;
  27109. vertexData.uvs = uvs;
  27110. if (faceColors) {
  27111. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27112. vertexData.colors = totalColors;
  27113. }
  27114. return vertexData;
  27115. };
  27116. /**
  27117. * Creates the VertexData of the Sphere.
  27118. */
  27119. VertexData.CreateSphere = function (options) {
  27120. var segments = options.segments || 32;
  27121. var diameterX = options.diameterX || options.diameter || 1;
  27122. var diameterY = options.diameterY || options.diameter || 1;
  27123. var diameterZ = options.diameterZ || options.diameter || 1;
  27124. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27125. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27126. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27127. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27128. var totalZRotationSteps = 2 + segments;
  27129. var totalYRotationSteps = 2 * totalZRotationSteps;
  27130. var indices = [];
  27131. var positions = [];
  27132. var normals = [];
  27133. var uvs = [];
  27134. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27135. var normalizedZ = zRotationStep / totalZRotationSteps;
  27136. var angleZ = normalizedZ * Math.PI * slice;
  27137. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27138. var normalizedY = yRotationStep / totalYRotationSteps;
  27139. var angleY = normalizedY * Math.PI * 2 * arc;
  27140. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27141. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27142. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27143. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27144. var vertex = complete.multiply(radius);
  27145. var normal = complete.divide(radius).normalize();
  27146. positions.push(vertex.x, vertex.y, vertex.z);
  27147. normals.push(normal.x, normal.y, normal.z);
  27148. uvs.push(normalizedY, normalizedZ);
  27149. }
  27150. if (zRotationStep > 0) {
  27151. var verticesCount = positions.length / 3;
  27152. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27153. indices.push((firstIndex));
  27154. indices.push((firstIndex + 1));
  27155. indices.push(firstIndex + totalYRotationSteps + 1);
  27156. indices.push((firstIndex + totalYRotationSteps + 1));
  27157. indices.push((firstIndex + 1));
  27158. indices.push((firstIndex + totalYRotationSteps + 2));
  27159. }
  27160. }
  27161. }
  27162. // Sides
  27163. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27164. // Result
  27165. var vertexData = new VertexData();
  27166. vertexData.indices = indices;
  27167. vertexData.positions = positions;
  27168. vertexData.normals = normals;
  27169. vertexData.uvs = uvs;
  27170. return vertexData;
  27171. };
  27172. /**
  27173. * Creates the VertexData of the Cylinder or Cone.
  27174. */
  27175. VertexData.CreateCylinder = function (options) {
  27176. var height = options.height || 2;
  27177. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27178. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27179. var tessellation = options.tessellation || 24;
  27180. var subdivisions = options.subdivisions || 1;
  27181. var hasRings = options.hasRings;
  27182. var enclose = options.enclose;
  27183. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27184. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27185. var faceUV = options.faceUV || new Array(3);
  27186. var faceColors = options.faceColors;
  27187. // default face colors and UV if undefined
  27188. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27189. var ringNb = (hasRings) ? subdivisions : 1;
  27190. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27191. var f;
  27192. for (f = 0; f < surfaceNb; f++) {
  27193. if (faceColors && faceColors[f] === undefined) {
  27194. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27195. }
  27196. }
  27197. for (f = 0; f < surfaceNb; f++) {
  27198. if (faceUV && faceUV[f] === undefined) {
  27199. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27200. }
  27201. }
  27202. var indices = [];
  27203. var positions = [];
  27204. var normals = [];
  27205. var uvs = [];
  27206. var colors = [];
  27207. var angle_step = Math.PI * 2 * arc / tessellation;
  27208. var angle;
  27209. var h;
  27210. var radius;
  27211. var tan = (diameterBottom - diameterTop) / 2 / height;
  27212. var ringVertex = BABYLON.Vector3.Zero();
  27213. var ringNormal = BABYLON.Vector3.Zero();
  27214. var ringFirstVertex = BABYLON.Vector3.Zero();
  27215. var ringFirstNormal = BABYLON.Vector3.Zero();
  27216. var quadNormal = BABYLON.Vector3.Zero();
  27217. var Y = BABYLON.Axis.Y;
  27218. // positions, normals, uvs
  27219. var i;
  27220. var j;
  27221. var r;
  27222. var ringIdx = 1;
  27223. var s = 1; // surface index
  27224. var cs = 0;
  27225. var v = 0;
  27226. for (i = 0; i <= subdivisions; i++) {
  27227. h = i / subdivisions;
  27228. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27229. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27230. for (r = 0; r < ringIdx; r++) {
  27231. if (hasRings) {
  27232. s += r;
  27233. }
  27234. if (enclose) {
  27235. s += 2 * r;
  27236. }
  27237. for (j = 0; j <= tessellation; j++) {
  27238. angle = j * angle_step;
  27239. // position
  27240. ringVertex.x = Math.cos(-angle) * radius;
  27241. ringVertex.y = -height / 2 + h * height;
  27242. ringVertex.z = Math.sin(-angle) * radius;
  27243. // normal
  27244. if (diameterTop === 0 && i === subdivisions) {
  27245. // if no top cap, reuse former normals
  27246. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27247. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27248. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27249. }
  27250. else {
  27251. ringNormal.x = ringVertex.x;
  27252. ringNormal.z = ringVertex.z;
  27253. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27254. ringNormal.normalize();
  27255. }
  27256. // keep first ring vertex values for enclose
  27257. if (j === 0) {
  27258. ringFirstVertex.copyFrom(ringVertex);
  27259. ringFirstNormal.copyFrom(ringNormal);
  27260. }
  27261. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27262. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27263. if (hasRings) {
  27264. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27265. }
  27266. else {
  27267. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27268. }
  27269. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27270. if (faceColors) {
  27271. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27272. }
  27273. }
  27274. // if enclose, add four vertices and their dedicated normals
  27275. if (arc !== 1 && enclose) {
  27276. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27277. positions.push(0, ringVertex.y, 0);
  27278. positions.push(0, ringVertex.y, 0);
  27279. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27280. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27281. quadNormal.normalize();
  27282. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27283. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27284. quadNormal.normalize();
  27285. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27286. if (hasRings) {
  27287. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27288. }
  27289. else {
  27290. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27291. }
  27292. uvs.push(faceUV[s + 1].x, v);
  27293. uvs.push(faceUV[s + 1].z, v);
  27294. if (hasRings) {
  27295. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27296. }
  27297. else {
  27298. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27299. }
  27300. uvs.push(faceUV[s + 2].x, v);
  27301. uvs.push(faceUV[s + 2].z, v);
  27302. if (faceColors) {
  27303. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27304. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27305. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27306. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27307. }
  27308. }
  27309. if (cs !== s) {
  27310. cs = s;
  27311. }
  27312. }
  27313. }
  27314. // indices
  27315. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27316. var s;
  27317. i = 0;
  27318. for (s = 0; s < subdivisions; s++) {
  27319. for (j = 0; j < tessellation; j++) {
  27320. var i0 = i * (e + 1) + j;
  27321. var i1 = (i + 1) * (e + 1) + j;
  27322. var i2 = i * (e + 1) + (j + 1);
  27323. var i3 = (i + 1) * (e + 1) + (j + 1);
  27324. indices.push(i0, i1, i2);
  27325. indices.push(i3, i2, i1);
  27326. }
  27327. if (arc !== 1 && enclose) {
  27328. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27329. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27330. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27331. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27332. }
  27333. i = (hasRings) ? (i + 2) : (i + 1);
  27334. }
  27335. // Caps
  27336. var createCylinderCap = function (isTop) {
  27337. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27338. if (radius === 0) {
  27339. return;
  27340. }
  27341. // Cap positions, normals & uvs
  27342. var angle;
  27343. var circleVector;
  27344. var i;
  27345. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27346. var c;
  27347. if (faceColors) {
  27348. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27349. }
  27350. // cap center
  27351. var vbase = positions.length / 3;
  27352. var offset = isTop ? height / 2 : -height / 2;
  27353. var center = new BABYLON.Vector3(0, offset, 0);
  27354. positions.push(center.x, center.y, center.z);
  27355. normals.push(0, isTop ? 1 : -1, 0);
  27356. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27357. if (faceColors) {
  27358. colors.push(c.r, c.g, c.b, c.a);
  27359. }
  27360. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27361. for (i = 0; i <= tessellation; i++) {
  27362. angle = Math.PI * 2 * i * arc / tessellation;
  27363. var cos = Math.cos(-angle);
  27364. var sin = Math.sin(-angle);
  27365. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27366. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27367. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27368. normals.push(0, isTop ? 1 : -1, 0);
  27369. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27370. if (faceColors) {
  27371. colors.push(c.r, c.g, c.b, c.a);
  27372. }
  27373. }
  27374. // Cap indices
  27375. for (i = 0; i < tessellation; i++) {
  27376. if (!isTop) {
  27377. indices.push(vbase);
  27378. indices.push(vbase + (i + 1));
  27379. indices.push(vbase + (i + 2));
  27380. }
  27381. else {
  27382. indices.push(vbase);
  27383. indices.push(vbase + (i + 2));
  27384. indices.push(vbase + (i + 1));
  27385. }
  27386. }
  27387. };
  27388. // add caps to geometry
  27389. createCylinderCap(false);
  27390. createCylinderCap(true);
  27391. // Sides
  27392. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27393. var vertexData = new VertexData();
  27394. vertexData.indices = indices;
  27395. vertexData.positions = positions;
  27396. vertexData.normals = normals;
  27397. vertexData.uvs = uvs;
  27398. if (faceColors) {
  27399. vertexData.colors = colors;
  27400. }
  27401. return vertexData;
  27402. };
  27403. /**
  27404. * Creates the VertexData of the Torus.
  27405. */
  27406. VertexData.CreateTorus = function (options) {
  27407. var indices = [];
  27408. var positions = [];
  27409. var normals = [];
  27410. var uvs = [];
  27411. var diameter = options.diameter || 1;
  27412. var thickness = options.thickness || 0.5;
  27413. var tessellation = options.tessellation || 16;
  27414. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27415. var stride = tessellation + 1;
  27416. for (var i = 0; i <= tessellation; i++) {
  27417. var u = i / tessellation;
  27418. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27419. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27420. for (var j = 0; j <= tessellation; j++) {
  27421. var v = 1 - j / tessellation;
  27422. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27423. var dx = Math.cos(innerAngle);
  27424. var dy = Math.sin(innerAngle);
  27425. // Create a vertex.
  27426. var normal = new BABYLON.Vector3(dx, dy, 0);
  27427. var position = normal.scale(thickness / 2);
  27428. var textureCoordinate = new BABYLON.Vector2(u, v);
  27429. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27430. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27431. positions.push(position.x, position.y, position.z);
  27432. normals.push(normal.x, normal.y, normal.z);
  27433. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27434. // And create indices for two triangles.
  27435. var nextI = (i + 1) % stride;
  27436. var nextJ = (j + 1) % stride;
  27437. indices.push(i * stride + j);
  27438. indices.push(i * stride + nextJ);
  27439. indices.push(nextI * stride + j);
  27440. indices.push(i * stride + nextJ);
  27441. indices.push(nextI * stride + nextJ);
  27442. indices.push(nextI * stride + j);
  27443. }
  27444. }
  27445. // Sides
  27446. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27447. // Result
  27448. var vertexData = new VertexData();
  27449. vertexData.indices = indices;
  27450. vertexData.positions = positions;
  27451. vertexData.normals = normals;
  27452. vertexData.uvs = uvs;
  27453. return vertexData;
  27454. };
  27455. /**
  27456. * Creates the VertexData of the LineSystem.
  27457. */
  27458. VertexData.CreateLineSystem = function (options) {
  27459. var indices = [];
  27460. var positions = [];
  27461. var lines = options.lines;
  27462. var idx = 0;
  27463. for (var l = 0; l < lines.length; l++) {
  27464. var points = lines[l];
  27465. for (var index = 0; index < points.length; index++) {
  27466. positions.push(points[index].x, points[index].y, points[index].z);
  27467. if (index > 0) {
  27468. indices.push(idx - 1);
  27469. indices.push(idx);
  27470. }
  27471. idx++;
  27472. }
  27473. }
  27474. var vertexData = new VertexData();
  27475. vertexData.indices = indices;
  27476. vertexData.positions = positions;
  27477. return vertexData;
  27478. };
  27479. /**
  27480. * Create the VertexData of the DashedLines.
  27481. */
  27482. VertexData.CreateDashedLines = function (options) {
  27483. var dashSize = options.dashSize || 3;
  27484. var gapSize = options.gapSize || 1;
  27485. var dashNb = options.dashNb || 200;
  27486. var points = options.points;
  27487. var positions = new Array();
  27488. var indices = new Array();
  27489. var curvect = BABYLON.Vector3.Zero();
  27490. var lg = 0;
  27491. var nb = 0;
  27492. var shft = 0;
  27493. var dashshft = 0;
  27494. var curshft = 0;
  27495. var idx = 0;
  27496. var i = 0;
  27497. for (i = 0; i < points.length - 1; i++) {
  27498. points[i + 1].subtractToRef(points[i], curvect);
  27499. lg += curvect.length();
  27500. }
  27501. shft = lg / dashNb;
  27502. dashshft = dashSize * shft / (dashSize + gapSize);
  27503. for (i = 0; i < points.length - 1; i++) {
  27504. points[i + 1].subtractToRef(points[i], curvect);
  27505. nb = Math.floor(curvect.length() / shft);
  27506. curvect.normalize();
  27507. for (var j = 0; j < nb; j++) {
  27508. curshft = shft * j;
  27509. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27510. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27511. indices.push(idx, idx + 1);
  27512. idx += 2;
  27513. }
  27514. }
  27515. // Result
  27516. var vertexData = new VertexData();
  27517. vertexData.positions = positions;
  27518. vertexData.indices = indices;
  27519. return vertexData;
  27520. };
  27521. /**
  27522. * Creates the VertexData of the Ground.
  27523. */
  27524. VertexData.CreateGround = function (options) {
  27525. var indices = [];
  27526. var positions = [];
  27527. var normals = [];
  27528. var uvs = [];
  27529. var row, col;
  27530. var width = options.width || 1;
  27531. var height = options.height || 1;
  27532. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27533. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27534. for (row = 0; row <= subdivisionsY; row++) {
  27535. for (col = 0; col <= subdivisionsX; col++) {
  27536. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27537. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27538. positions.push(position.x, position.y, position.z);
  27539. normals.push(normal.x, normal.y, normal.z);
  27540. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27541. }
  27542. }
  27543. for (row = 0; row < subdivisionsY; row++) {
  27544. for (col = 0; col < subdivisionsX; col++) {
  27545. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27546. indices.push(col + 1 + row * (subdivisionsX + 1));
  27547. indices.push(col + row * (subdivisionsX + 1));
  27548. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27549. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27550. indices.push(col + row * (subdivisionsX + 1));
  27551. }
  27552. }
  27553. // Result
  27554. var vertexData = new VertexData();
  27555. vertexData.indices = indices;
  27556. vertexData.positions = positions;
  27557. vertexData.normals = normals;
  27558. vertexData.uvs = uvs;
  27559. return vertexData;
  27560. };
  27561. /**
  27562. * Creates the VertexData of the TiledGround.
  27563. */
  27564. VertexData.CreateTiledGround = function (options) {
  27565. var xmin = options.xmin || -1.0;
  27566. var zmin = options.zmin || -1.0;
  27567. var xmax = options.xmax || 1.0;
  27568. var zmax = options.zmax || 1.0;
  27569. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27570. var precision = options.precision || { w: 1, h: 1 };
  27571. var indices = [];
  27572. var positions = [];
  27573. var normals = [];
  27574. var uvs = [];
  27575. var row, col, tileRow, tileCol;
  27576. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27577. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27578. precision.w = (precision.w < 1) ? 1 : precision.w;
  27579. precision.h = (precision.h < 1) ? 1 : precision.h;
  27580. var tileSize = {
  27581. 'w': (xmax - xmin) / subdivisions.w,
  27582. 'h': (zmax - zmin) / subdivisions.h
  27583. };
  27584. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27585. // Indices
  27586. var base = positions.length / 3;
  27587. var rowLength = precision.w + 1;
  27588. for (row = 0; row < precision.h; row++) {
  27589. for (col = 0; col < precision.w; col++) {
  27590. var square = [
  27591. base + col + row * rowLength,
  27592. base + (col + 1) + row * rowLength,
  27593. base + (col + 1) + (row + 1) * rowLength,
  27594. base + col + (row + 1) * rowLength
  27595. ];
  27596. indices.push(square[1]);
  27597. indices.push(square[2]);
  27598. indices.push(square[3]);
  27599. indices.push(square[0]);
  27600. indices.push(square[1]);
  27601. indices.push(square[3]);
  27602. }
  27603. }
  27604. // Position, normals and uvs
  27605. var position = BABYLON.Vector3.Zero();
  27606. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27607. for (row = 0; row <= precision.h; row++) {
  27608. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27609. for (col = 0; col <= precision.w; col++) {
  27610. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27611. position.y = 0;
  27612. positions.push(position.x, position.y, position.z);
  27613. normals.push(normal.x, normal.y, normal.z);
  27614. uvs.push(col / precision.w, row / precision.h);
  27615. }
  27616. }
  27617. }
  27618. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27619. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27620. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27621. }
  27622. }
  27623. // Result
  27624. var vertexData = new VertexData();
  27625. vertexData.indices = indices;
  27626. vertexData.positions = positions;
  27627. vertexData.normals = normals;
  27628. vertexData.uvs = uvs;
  27629. return vertexData;
  27630. };
  27631. /**
  27632. * Creates the VertexData of the Ground designed from a heightmap.
  27633. */
  27634. VertexData.CreateGroundFromHeightMap = function (options) {
  27635. var indices = [];
  27636. var positions = [];
  27637. var normals = [];
  27638. var uvs = [];
  27639. var row, col;
  27640. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27641. // Vertices
  27642. for (row = 0; row <= options.subdivisions; row++) {
  27643. for (col = 0; col <= options.subdivisions; col++) {
  27644. 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));
  27645. // Compute height
  27646. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27647. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27648. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27649. var r = options.buffer[pos] / 255.0;
  27650. var g = options.buffer[pos + 1] / 255.0;
  27651. var b = options.buffer[pos + 2] / 255.0;
  27652. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27653. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27654. // Add vertex
  27655. positions.push(position.x, position.y, position.z);
  27656. normals.push(0, 0, 0);
  27657. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27658. }
  27659. }
  27660. // Indices
  27661. for (row = 0; row < options.subdivisions; row++) {
  27662. for (col = 0; col < options.subdivisions; col++) {
  27663. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27664. indices.push(col + 1 + row * (options.subdivisions + 1));
  27665. indices.push(col + row * (options.subdivisions + 1));
  27666. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27667. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27668. indices.push(col + row * (options.subdivisions + 1));
  27669. }
  27670. }
  27671. // Normals
  27672. VertexData.ComputeNormals(positions, indices, normals);
  27673. // Result
  27674. var vertexData = new VertexData();
  27675. vertexData.indices = indices;
  27676. vertexData.positions = positions;
  27677. vertexData.normals = normals;
  27678. vertexData.uvs = uvs;
  27679. return vertexData;
  27680. };
  27681. /**
  27682. * Creates the VertexData of the Plane.
  27683. */
  27684. VertexData.CreatePlane = function (options) {
  27685. var indices = [];
  27686. var positions = [];
  27687. var normals = [];
  27688. var uvs = [];
  27689. var width = options.width || options.size || 1;
  27690. var height = options.height || options.size || 1;
  27691. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27692. // Vertices
  27693. var halfWidth = width / 2.0;
  27694. var halfHeight = height / 2.0;
  27695. positions.push(-halfWidth, -halfHeight, 0);
  27696. normals.push(0, 0, -1.0);
  27697. uvs.push(0.0, 0.0);
  27698. positions.push(halfWidth, -halfHeight, 0);
  27699. normals.push(0, 0, -1.0);
  27700. uvs.push(1.0, 0.0);
  27701. positions.push(halfWidth, halfHeight, 0);
  27702. normals.push(0, 0, -1.0);
  27703. uvs.push(1.0, 1.0);
  27704. positions.push(-halfWidth, halfHeight, 0);
  27705. normals.push(0, 0, -1.0);
  27706. uvs.push(0.0, 1.0);
  27707. // Indices
  27708. indices.push(0);
  27709. indices.push(1);
  27710. indices.push(2);
  27711. indices.push(0);
  27712. indices.push(2);
  27713. indices.push(3);
  27714. // Sides
  27715. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27716. // Result
  27717. var vertexData = new VertexData();
  27718. vertexData.indices = indices;
  27719. vertexData.positions = positions;
  27720. vertexData.normals = normals;
  27721. vertexData.uvs = uvs;
  27722. return vertexData;
  27723. };
  27724. /**
  27725. * Creates the VertexData of the Disc or regular Polygon.
  27726. */
  27727. VertexData.CreateDisc = function (options) {
  27728. var positions = [];
  27729. var indices = [];
  27730. var normals = [];
  27731. var uvs = [];
  27732. var radius = options.radius || 0.5;
  27733. var tessellation = options.tessellation || 64;
  27734. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27735. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27736. // positions and uvs
  27737. positions.push(0, 0, 0); // disc center first
  27738. uvs.push(0.5, 0.5);
  27739. var theta = Math.PI * 2 * arc;
  27740. var step = theta / tessellation;
  27741. for (var a = 0; a < theta; a += step) {
  27742. var x = Math.cos(a);
  27743. var y = Math.sin(a);
  27744. var u = (x + 1) / 2;
  27745. var v = (1 - y) / 2;
  27746. positions.push(radius * x, radius * y, 0);
  27747. uvs.push(u, v);
  27748. }
  27749. if (arc === 1) {
  27750. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27751. uvs.push(uvs[2], uvs[3]);
  27752. }
  27753. //indices
  27754. var vertexNb = positions.length / 3;
  27755. for (var i = 1; i < vertexNb - 1; i++) {
  27756. indices.push(i + 1, 0, i);
  27757. }
  27758. // result
  27759. VertexData.ComputeNormals(positions, indices, normals);
  27760. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27761. var vertexData = new VertexData();
  27762. vertexData.indices = indices;
  27763. vertexData.positions = positions;
  27764. vertexData.normals = normals;
  27765. vertexData.uvs = uvs;
  27766. return vertexData;
  27767. };
  27768. /**
  27769. * Re-creates the VertexData of the Polygon for sideOrientation.
  27770. */
  27771. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  27772. var faceUV = fUV || new Array(3);
  27773. var faceColors = fColors;
  27774. var colors = [];
  27775. // default face colors and UV if undefined
  27776. for (var f = 0; f < 3; f++) {
  27777. if (faceUV[f] === undefined) {
  27778. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27779. }
  27780. if (faceColors && faceColors[f] === undefined) {
  27781. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27782. }
  27783. }
  27784. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27785. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27786. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27787. var indices = polygon.getIndices();
  27788. // set face colours and textures
  27789. var idx = 0;
  27790. var face = 0;
  27791. for (var index = 0; index < normals.length; index += 3) {
  27792. //Edge Face no. 1
  27793. if (Math.abs(normals[index + 1]) < 0.001) {
  27794. face = 1;
  27795. }
  27796. //Top Face no. 0
  27797. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  27798. face = 0;
  27799. }
  27800. //Bottom Face no. 2
  27801. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  27802. face = 2;
  27803. }
  27804. idx = index / 3;
  27805. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  27806. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  27807. if (faceColors) {
  27808. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  27809. }
  27810. }
  27811. // sides
  27812. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  27813. // Result
  27814. var vertexData = new VertexData();
  27815. vertexData.indices = indices;
  27816. vertexData.positions = positions;
  27817. vertexData.normals = normals;
  27818. vertexData.uvs = uvs;
  27819. if (faceColors) {
  27820. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27821. vertexData.colors = totalColors;
  27822. }
  27823. return vertexData;
  27824. };
  27825. /**
  27826. * Creates the VertexData of the IcoSphere.
  27827. */
  27828. VertexData.CreateIcoSphere = function (options) {
  27829. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27830. var radius = options.radius || 1;
  27831. var flat = (options.flat === undefined) ? true : options.flat;
  27832. var subdivisions = options.subdivisions || 4;
  27833. var radiusX = options.radiusX || radius;
  27834. var radiusY = options.radiusY || radius;
  27835. var radiusZ = options.radiusZ || radius;
  27836. var t = (1 + Math.sqrt(5)) / 2;
  27837. // 12 vertex x,y,z
  27838. var ico_vertices = [
  27839. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27840. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27841. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27842. ];
  27843. // index of 3 vertex makes a face of icopshere
  27844. var ico_indices = [
  27845. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27846. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27847. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27848. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27849. ];
  27850. // vertex for uv have aliased position, not for UV
  27851. var vertices_unalias_id = [
  27852. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27853. // vertex alias
  27854. 0,
  27855. 2,
  27856. 3,
  27857. 3,
  27858. 3,
  27859. 4,
  27860. 7,
  27861. 8,
  27862. 9,
  27863. 9,
  27864. 10,
  27865. 11 // 23: B + 12
  27866. ];
  27867. // uv as integer step (not pixels !)
  27868. var ico_vertexuv = [
  27869. 5, 1, 3, 1, 6, 4, 0, 0,
  27870. 5, 3, 4, 2, 2, 2, 4, 0,
  27871. 2, 0, 1, 1, 6, 0, 6, 2,
  27872. // vertex alias (for same vertex on different faces)
  27873. 0, 4,
  27874. 3, 3,
  27875. 4, 4,
  27876. 3, 1,
  27877. 4, 2,
  27878. 4, 4,
  27879. 0, 2,
  27880. 1, 1,
  27881. 2, 2,
  27882. 3, 3,
  27883. 1, 3,
  27884. 2, 4 // 23: B + 12
  27885. ];
  27886. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27887. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27888. // First island of uv mapping
  27889. // v = 4h 3+ 2
  27890. // v = 3h 9+ 4
  27891. // v = 2h 9+ 5 B
  27892. // v = 1h 9 1 0
  27893. // v = 0h 3 8 7 A
  27894. // u = 0 1 2 3 4 5 6 *a
  27895. // Second island of uv mapping
  27896. // v = 4h 0+ B+ 4+
  27897. // v = 3h A+ 2+
  27898. // v = 2h 7+ 6 3+
  27899. // v = 1h 8+ 3+
  27900. // v = 0h
  27901. // u = 0 1 2 3 4 5 6 *a
  27902. // Face layout on texture UV mapping
  27903. // ============
  27904. // \ 4 /\ 16 / ======
  27905. // \ / \ / /\ 11 /
  27906. // \/ 7 \/ / \ /
  27907. // ======= / 10 \/
  27908. // /\ 17 /\ =======
  27909. // / \ / \ \ 15 /\
  27910. // / 8 \/ 12 \ \ / \
  27911. // ============ \/ 6 \
  27912. // \ 18 /\ ============
  27913. // \ / \ \ 5 /\ 0 /
  27914. // \/ 13 \ \ / \ /
  27915. // ======= \/ 1 \/
  27916. // =============
  27917. // /\ 19 /\ 2 /\
  27918. // / \ / \ / \
  27919. // / 14 \/ 9 \/ 3 \
  27920. // ===================
  27921. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27922. var ustep = 138 / 1024;
  27923. var vstep = 239 / 1024;
  27924. var uoffset = 60 / 1024;
  27925. var voffset = 26 / 1024;
  27926. // Second island should have margin, not to touch the first island
  27927. // avoid any borderline artefact in pixel rounding
  27928. var island_u_offset = -40 / 1024;
  27929. var island_v_offset = +20 / 1024;
  27930. // face is either island 0 or 1 :
  27931. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27932. var island = [
  27933. 0, 0, 0, 0, 1,
  27934. 0, 0, 1, 1, 0,
  27935. 0, 0, 1, 1, 0,
  27936. 0, 1, 1, 1, 0 // 15 - 19
  27937. ];
  27938. var indices = [];
  27939. var positions = [];
  27940. var normals = [];
  27941. var uvs = [];
  27942. var current_indice = 0;
  27943. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27944. var face_vertex_pos = new Array(3);
  27945. var face_vertex_uv = new Array(3);
  27946. var v012;
  27947. for (v012 = 0; v012 < 3; v012++) {
  27948. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27949. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27950. }
  27951. // create all with normals
  27952. for (var face = 0; face < 20; face++) {
  27953. // 3 vertex per face
  27954. for (v012 = 0; v012 < 3; v012++) {
  27955. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27956. var v_id = ico_indices[3 * face + v012];
  27957. // vertex have 3D position (x,y,z)
  27958. 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]);
  27959. // Normalize to get normal, then scale to radius
  27960. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27961. // uv Coordinates from vertex ID
  27962. 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);
  27963. }
  27964. // Subdivide the face (interpolate pos, norm, uv)
  27965. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27966. // - norm is linear interpolation of vertex corner normal
  27967. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27968. // - uv is linear interpolation
  27969. //
  27970. // Topology is as below for sub-divide by 2
  27971. // vertex shown as v0,v1,v2
  27972. // interp index is i1 to progress in range [v0,v1[
  27973. // interp index is i2 to progress in range [v0,v2[
  27974. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27975. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27976. //
  27977. //
  27978. // i2 v2
  27979. // ^ ^
  27980. // / / \
  27981. // / / \
  27982. // / / \
  27983. // / / (0,1) \
  27984. // / #---------\
  27985. // / / \ (0,0)'/ \
  27986. // / / \ / \
  27987. // / / \ / \
  27988. // / / (0,0) \ / (1,0) \
  27989. // / #---------#---------\
  27990. // v0 v1
  27991. //
  27992. // --------------------> i1
  27993. //
  27994. // interp of (i1,i2):
  27995. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27996. // along i1 : lerp(x0,x1, i1/(S-i2))
  27997. //
  27998. // centroid of triangle is needed to get help normal computation
  27999. // (c1,c2) are used for centroid location
  28000. var interp_vertex = function (i1, i2, c1, c2) {
  28001. // vertex is interpolated from
  28002. // - face_vertex_pos[0..2]
  28003. // - face_vertex_uv[0..2]
  28004. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28005. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28006. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28007. pos_interp.normalize();
  28008. var vertex_normal;
  28009. if (flat) {
  28010. // in flat mode, recalculate normal as face centroid normal
  28011. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28012. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28013. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28014. }
  28015. else {
  28016. // in smooth mode, recalculate normal from each single vertex position
  28017. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28018. }
  28019. // Vertex normal need correction due to X,Y,Z radius scaling
  28020. vertex_normal.x /= radiusX;
  28021. vertex_normal.y /= radiusY;
  28022. vertex_normal.z /= radiusZ;
  28023. vertex_normal.normalize();
  28024. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28025. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28026. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28027. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28028. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28029. uvs.push(uv_interp.x, uv_interp.y);
  28030. // push each vertex has member of a face
  28031. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28032. indices.push(current_indice);
  28033. current_indice++;
  28034. };
  28035. for (var i2 = 0; i2 < subdivisions; i2++) {
  28036. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28037. // face : (i1,i2) for /\ :
  28038. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28039. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28040. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28041. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28042. if (i1 + i2 + 1 < subdivisions) {
  28043. // face : (i1,i2)' for \/ :
  28044. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28045. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28046. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28047. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28048. }
  28049. }
  28050. }
  28051. }
  28052. // Sides
  28053. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28054. // Result
  28055. var vertexData = new VertexData();
  28056. vertexData.indices = indices;
  28057. vertexData.positions = positions;
  28058. vertexData.normals = normals;
  28059. vertexData.uvs = uvs;
  28060. return vertexData;
  28061. };
  28062. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28063. /**
  28064. * Creates the VertexData of the Polyhedron.
  28065. */
  28066. VertexData.CreatePolyhedron = function (options) {
  28067. // provided polyhedron types :
  28068. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28069. // 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)
  28070. var polyhedra = [];
  28071. 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]] };
  28072. 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]] };
  28073. polyhedra[2] = {
  28074. 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]],
  28075. 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]]
  28076. };
  28077. polyhedra[3] = {
  28078. 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]],
  28079. 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]]
  28080. };
  28081. polyhedra[4] = {
  28082. 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]],
  28083. 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]]
  28084. };
  28085. 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]] };
  28086. 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]] };
  28087. 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]] };
  28088. 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]] };
  28089. 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]] };
  28090. 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]] };
  28091. 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]] };
  28092. 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]] };
  28093. 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]] };
  28094. polyhedra[14] = {
  28095. 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]],
  28096. 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]]
  28097. };
  28098. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28099. var size = options.size;
  28100. var sizeX = options.sizeX || size || 1;
  28101. var sizeY = options.sizeY || size || 1;
  28102. var sizeZ = options.sizeZ || size || 1;
  28103. var data = options.custom || polyhedra[type];
  28104. var nbfaces = data.face.length;
  28105. var faceUV = options.faceUV || new Array(nbfaces);
  28106. var faceColors = options.faceColors;
  28107. var flat = (options.flat === undefined) ? true : options.flat;
  28108. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28109. var positions = [];
  28110. var indices = [];
  28111. var normals = [];
  28112. var uvs = [];
  28113. var colors = [];
  28114. var index = 0;
  28115. var faceIdx = 0; // face cursor in the array "indexes"
  28116. var indexes = [];
  28117. var i = 0;
  28118. var f = 0;
  28119. var u, v, ang, x, y, tmp;
  28120. // default face colors and UV if undefined
  28121. if (flat) {
  28122. for (f = 0; f < nbfaces; f++) {
  28123. if (faceColors && faceColors[f] === undefined) {
  28124. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28125. }
  28126. if (faceUV && faceUV[f] === undefined) {
  28127. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28128. }
  28129. }
  28130. }
  28131. if (!flat) {
  28132. for (i = 0; i < data.vertex.length; i++) {
  28133. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28134. uvs.push(0, 0);
  28135. }
  28136. for (f = 0; f < nbfaces; f++) {
  28137. for (i = 0; i < data.face[f].length - 2; i++) {
  28138. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28139. }
  28140. }
  28141. }
  28142. else {
  28143. for (f = 0; f < nbfaces; f++) {
  28144. var fl = data.face[f].length; // number of vertices of the current face
  28145. ang = 2 * Math.PI / fl;
  28146. x = 0.5 * Math.tan(ang / 2);
  28147. y = 0.5;
  28148. // positions, uvs, colors
  28149. for (i = 0; i < fl; i++) {
  28150. // positions
  28151. 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);
  28152. indexes.push(index);
  28153. index++;
  28154. // uvs
  28155. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28156. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28157. uvs.push(u, v);
  28158. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28159. y = x * Math.sin(ang) + y * Math.cos(ang);
  28160. x = tmp;
  28161. // colors
  28162. if (faceColors) {
  28163. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28164. }
  28165. }
  28166. // indices from indexes
  28167. for (i = 0; i < fl - 2; i++) {
  28168. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28169. }
  28170. faceIdx += fl;
  28171. }
  28172. }
  28173. VertexData.ComputeNormals(positions, indices, normals);
  28174. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28175. var vertexData = new VertexData();
  28176. vertexData.positions = positions;
  28177. vertexData.indices = indices;
  28178. vertexData.normals = normals;
  28179. vertexData.uvs = uvs;
  28180. if (faceColors && flat) {
  28181. vertexData.colors = colors;
  28182. }
  28183. return vertexData;
  28184. };
  28185. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28186. /**
  28187. * Creates the VertexData of the Torus Knot.
  28188. */
  28189. VertexData.CreateTorusKnot = function (options) {
  28190. var indices = [];
  28191. var positions = [];
  28192. var normals = [];
  28193. var uvs = [];
  28194. var radius = options.radius || 2;
  28195. var tube = options.tube || 0.5;
  28196. var radialSegments = options.radialSegments || 32;
  28197. var tubularSegments = options.tubularSegments || 32;
  28198. var p = options.p || 2;
  28199. var q = options.q || 3;
  28200. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28201. // Helper
  28202. var getPos = function (angle) {
  28203. var cu = Math.cos(angle);
  28204. var su = Math.sin(angle);
  28205. var quOverP = q / p * angle;
  28206. var cs = Math.cos(quOverP);
  28207. var tx = radius * (2 + cs) * 0.5 * cu;
  28208. var ty = radius * (2 + cs) * su * 0.5;
  28209. var tz = radius * Math.sin(quOverP) * 0.5;
  28210. return new BABYLON.Vector3(tx, ty, tz);
  28211. };
  28212. // Vertices
  28213. var i;
  28214. var j;
  28215. for (i = 0; i <= radialSegments; i++) {
  28216. var modI = i % radialSegments;
  28217. var u = modI / radialSegments * 2 * p * Math.PI;
  28218. var p1 = getPos(u);
  28219. var p2 = getPos(u + 0.01);
  28220. var tang = p2.subtract(p1);
  28221. var n = p2.add(p1);
  28222. var bitan = BABYLON.Vector3.Cross(tang, n);
  28223. n = BABYLON.Vector3.Cross(bitan, tang);
  28224. bitan.normalize();
  28225. n.normalize();
  28226. for (j = 0; j < tubularSegments; j++) {
  28227. var modJ = j % tubularSegments;
  28228. var v = modJ / tubularSegments * 2 * Math.PI;
  28229. var cx = -tube * Math.cos(v);
  28230. var cy = tube * Math.sin(v);
  28231. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28232. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28233. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28234. uvs.push(i / radialSegments);
  28235. uvs.push(j / tubularSegments);
  28236. }
  28237. }
  28238. for (i = 0; i < radialSegments; i++) {
  28239. for (j = 0; j < tubularSegments; j++) {
  28240. var jNext = (j + 1) % tubularSegments;
  28241. var a = i * tubularSegments + j;
  28242. var b = (i + 1) * tubularSegments + j;
  28243. var c = (i + 1) * tubularSegments + jNext;
  28244. var d = i * tubularSegments + jNext;
  28245. indices.push(d);
  28246. indices.push(b);
  28247. indices.push(a);
  28248. indices.push(d);
  28249. indices.push(c);
  28250. indices.push(b);
  28251. }
  28252. }
  28253. // Normals
  28254. VertexData.ComputeNormals(positions, indices, normals);
  28255. // Sides
  28256. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28257. // Result
  28258. var vertexData = new VertexData();
  28259. vertexData.indices = indices;
  28260. vertexData.positions = positions;
  28261. vertexData.normals = normals;
  28262. vertexData.uvs = uvs;
  28263. return vertexData;
  28264. };
  28265. // Tools
  28266. /**
  28267. * @param {any} - positions (number[] or Float32Array)
  28268. * @param {any} - indices (number[] or Uint16Array)
  28269. * @param {any} - normals (number[] or Float32Array)
  28270. * options (optional) :
  28271. * facetPositions : optional array of facet positions (vector3)
  28272. * facetNormals : optional array of facet normals (vector3)
  28273. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28274. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28275. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28276. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28277. * bInfo : optional bounding info, required for facetPartitioning computation
  28278. */
  28279. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28280. // temporary scalar variables
  28281. var index = 0; // facet index
  28282. var p1p2x = 0.0; // p1p2 vector x coordinate
  28283. var p1p2y = 0.0; // p1p2 vector y coordinate
  28284. var p1p2z = 0.0; // p1p2 vector z coordinate
  28285. var p3p2x = 0.0; // p3p2 vector x coordinate
  28286. var p3p2y = 0.0; // p3p2 vector y coordinate
  28287. var p3p2z = 0.0; // p3p2 vector z coordinate
  28288. var faceNormalx = 0.0; // facet normal x coordinate
  28289. var faceNormaly = 0.0; // facet normal y coordinate
  28290. var faceNormalz = 0.0; // facet normal z coordinate
  28291. var length = 0.0; // facet normal length before normalization
  28292. var v1x = 0; // vector1 x index in the positions array
  28293. var v1y = 0; // vector1 y index in the positions array
  28294. var v1z = 0; // vector1 z index in the positions array
  28295. var v2x = 0; // vector2 x index in the positions array
  28296. var v2y = 0; // vector2 y index in the positions array
  28297. var v2z = 0; // vector2 z index in the positions array
  28298. var v3x = 0; // vector3 x index in the positions array
  28299. var v3y = 0; // vector3 y index in the positions array
  28300. var v3z = 0; // vector3 z index in the positions array
  28301. var computeFacetNormals = false;
  28302. var computeFacetPositions = false;
  28303. var computeFacetPartitioning = false;
  28304. var faceNormalSign = 1;
  28305. if (options) {
  28306. computeFacetNormals = (options.facetNormals) ? true : false;
  28307. computeFacetPositions = (options.facetPositions) ? true : false;
  28308. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28309. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28310. }
  28311. // facetPartitioning reinit if needed
  28312. if (computeFacetPartitioning) {
  28313. var ox = 0; // X partitioning index for facet position
  28314. var oy = 0; // Y partinioning index for facet position
  28315. var oz = 0; // Z partinioning index for facet position
  28316. var b1x = 0; // X partitioning index for facet v1 vertex
  28317. var b1y = 0; // Y partitioning index for facet v1 vertex
  28318. var b1z = 0; // z partitioning index for facet v1 vertex
  28319. var b2x = 0; // X partitioning index for facet v2 vertex
  28320. var b2y = 0; // Y partitioning index for facet v2 vertex
  28321. var b2z = 0; // Z partitioning index for facet v2 vertex
  28322. var b3x = 0; // X partitioning index for facet v3 vertex
  28323. var b3y = 0; // Y partitioning index for facet v3 vertex
  28324. var b3z = 0; // Z partitioning index for facet v3 vertex
  28325. var block_idx_o = 0; // facet barycenter block index
  28326. var block_idx_v1 = 0; // v1 vertex block index
  28327. var block_idx_v2 = 0; // v2 vertex block index
  28328. var block_idx_v3 = 0; // v3 vertex block index
  28329. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28330. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28331. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28332. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28333. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28334. var subSq = options.subDiv.max * options.subDiv.max;
  28335. options.facetPartitioning.length = 0;
  28336. }
  28337. // reset the normals
  28338. for (index = 0; index < positions.length; index++) {
  28339. normals[index] = 0.0;
  28340. }
  28341. // Loop : 1 indice triplet = 1 facet
  28342. var nbFaces = indices.length / 3;
  28343. for (index = 0; index < nbFaces; index++) {
  28344. // get the indexes of the coordinates of each vertex of the facet
  28345. v1x = indices[index * 3] * 3;
  28346. v1y = v1x + 1;
  28347. v1z = v1x + 2;
  28348. v2x = indices[index * 3 + 1] * 3;
  28349. v2y = v2x + 1;
  28350. v2z = v2x + 2;
  28351. v3x = indices[index * 3 + 2] * 3;
  28352. v3y = v3x + 1;
  28353. v3z = v3x + 2;
  28354. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28355. p1p2y = positions[v1y] - positions[v2y];
  28356. p1p2z = positions[v1z] - positions[v2z];
  28357. p3p2x = positions[v3x] - positions[v2x];
  28358. p3p2y = positions[v3y] - positions[v2y];
  28359. p3p2z = positions[v3z] - positions[v2z];
  28360. // compute the face normal with the cross product
  28361. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28362. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28363. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28364. // normalize this normal and store it in the array facetData
  28365. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28366. length = (length === 0) ? 1.0 : length;
  28367. faceNormalx /= length;
  28368. faceNormaly /= length;
  28369. faceNormalz /= length;
  28370. if (computeFacetNormals) {
  28371. options.facetNormals[index].x = faceNormalx;
  28372. options.facetNormals[index].y = faceNormaly;
  28373. options.facetNormals[index].z = faceNormalz;
  28374. }
  28375. if (computeFacetPositions) {
  28376. // compute and the facet barycenter coordinates in the array facetPositions
  28377. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28378. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28379. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28380. }
  28381. if (computeFacetPartitioning) {
  28382. // store the facet indexes in arrays in the main facetPartitioning array :
  28383. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28384. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28385. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28386. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28387. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28388. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28389. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28390. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28391. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28392. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28393. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28394. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28395. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28396. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28397. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28398. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28399. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28400. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28401. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28402. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28403. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28404. // push each facet index in each block containing the vertex
  28405. options.facetPartitioning[block_idx_v1].push(index);
  28406. if (block_idx_v2 != block_idx_v1) {
  28407. options.facetPartitioning[block_idx_v2].push(index);
  28408. }
  28409. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28410. options.facetPartitioning[block_idx_v3].push(index);
  28411. }
  28412. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28413. options.facetPartitioning[block_idx_o].push(index);
  28414. }
  28415. }
  28416. // compute the normals anyway
  28417. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28418. normals[v1y] += faceNormaly;
  28419. normals[v1z] += faceNormalz;
  28420. normals[v2x] += faceNormalx;
  28421. normals[v2y] += faceNormaly;
  28422. normals[v2z] += faceNormalz;
  28423. normals[v3x] += faceNormalx;
  28424. normals[v3y] += faceNormaly;
  28425. normals[v3z] += faceNormalz;
  28426. }
  28427. // last normalization of each normal
  28428. for (index = 0; index < normals.length / 3; index++) {
  28429. faceNormalx = normals[index * 3];
  28430. faceNormaly = normals[index * 3 + 1];
  28431. faceNormalz = normals[index * 3 + 2];
  28432. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28433. length = (length === 0) ? 1.0 : length;
  28434. faceNormalx /= length;
  28435. faceNormaly /= length;
  28436. faceNormalz /= length;
  28437. normals[index * 3] = faceNormalx;
  28438. normals[index * 3 + 1] = faceNormaly;
  28439. normals[index * 3 + 2] = faceNormalz;
  28440. }
  28441. };
  28442. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28443. var li = indices.length;
  28444. var ln = normals.length;
  28445. var i;
  28446. var n;
  28447. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28448. switch (sideOrientation) {
  28449. case BABYLON.Mesh.FRONTSIDE:
  28450. // nothing changed
  28451. break;
  28452. case BABYLON.Mesh.BACKSIDE:
  28453. var tmp;
  28454. // indices
  28455. for (i = 0; i < li; i += 3) {
  28456. tmp = indices[i];
  28457. indices[i] = indices[i + 2];
  28458. indices[i + 2] = tmp;
  28459. }
  28460. // normals
  28461. for (n = 0; n < ln; n++) {
  28462. normals[n] = -normals[n];
  28463. }
  28464. break;
  28465. case BABYLON.Mesh.DOUBLESIDE:
  28466. // positions
  28467. var lp = positions.length;
  28468. var l = lp / 3;
  28469. for (var p = 0; p < lp; p++) {
  28470. positions[lp + p] = positions[p];
  28471. }
  28472. // indices
  28473. for (i = 0; i < li; i += 3) {
  28474. indices[i + li] = indices[i + 2] + l;
  28475. indices[i + 1 + li] = indices[i + 1] + l;
  28476. indices[i + 2 + li] = indices[i] + l;
  28477. }
  28478. // normals
  28479. for (n = 0; n < ln; n++) {
  28480. normals[ln + n] = -normals[n];
  28481. }
  28482. // uvs
  28483. var lu = uvs.length;
  28484. var u = 0;
  28485. for (u = 0; u < lu; u++) {
  28486. uvs[u + lu] = uvs[u];
  28487. }
  28488. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28489. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28490. u = 0;
  28491. for (i = 0; i < lu / 2; i++) {
  28492. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28493. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28494. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28495. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28496. u += 2;
  28497. }
  28498. break;
  28499. }
  28500. };
  28501. /**
  28502. * Creates a new VertexData from the imported parameters.
  28503. */
  28504. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28505. var vertexData = new VertexData();
  28506. // positions
  28507. var positions = parsedVertexData.positions;
  28508. if (positions) {
  28509. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28510. }
  28511. // normals
  28512. var normals = parsedVertexData.normals;
  28513. if (normals) {
  28514. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28515. }
  28516. // tangents
  28517. var tangents = parsedVertexData.tangents;
  28518. if (tangents) {
  28519. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28520. }
  28521. // uvs
  28522. var uvs = parsedVertexData.uvs;
  28523. if (uvs) {
  28524. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28525. }
  28526. // uv2s
  28527. var uv2s = parsedVertexData.uv2s;
  28528. if (uv2s) {
  28529. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28530. }
  28531. // uv3s
  28532. var uv3s = parsedVertexData.uv3s;
  28533. if (uv3s) {
  28534. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28535. }
  28536. // uv4s
  28537. var uv4s = parsedVertexData.uv4s;
  28538. if (uv4s) {
  28539. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28540. }
  28541. // uv5s
  28542. var uv5s = parsedVertexData.uv5s;
  28543. if (uv5s) {
  28544. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28545. }
  28546. // uv6s
  28547. var uv6s = parsedVertexData.uv6s;
  28548. if (uv6s) {
  28549. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28550. }
  28551. // colors
  28552. var colors = parsedVertexData.colors;
  28553. if (colors) {
  28554. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28555. }
  28556. // matricesIndices
  28557. var matricesIndices = parsedVertexData.matricesIndices;
  28558. if (matricesIndices) {
  28559. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28560. }
  28561. // matricesWeights
  28562. var matricesWeights = parsedVertexData.matricesWeights;
  28563. if (matricesWeights) {
  28564. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28565. }
  28566. // indices
  28567. var indices = parsedVertexData.indices;
  28568. if (indices) {
  28569. vertexData.indices = indices;
  28570. }
  28571. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28572. };
  28573. return VertexData;
  28574. }());
  28575. BABYLON.VertexData = VertexData;
  28576. })(BABYLON || (BABYLON = {}));
  28577. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28578. var BABYLON;
  28579. (function (BABYLON) {
  28580. var Geometry = (function () {
  28581. function Geometry(id, scene, vertexData, updatable, mesh) {
  28582. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28583. this._totalVertices = 0;
  28584. this._isDisposed = false;
  28585. this.id = id;
  28586. this._engine = scene.getEngine();
  28587. this._meshes = [];
  28588. this._scene = scene;
  28589. //Init vertex buffer cache
  28590. this._vertexBuffers = {};
  28591. this._indices = [];
  28592. this._updatable = updatable;
  28593. // vertexData
  28594. if (vertexData) {
  28595. this.setAllVerticesData(vertexData, updatable);
  28596. }
  28597. else {
  28598. this._totalVertices = 0;
  28599. this._indices = [];
  28600. }
  28601. if (this._engine.getCaps().vertexArrayObject) {
  28602. this._vertexArrayObjects = {};
  28603. }
  28604. // applyToMesh
  28605. if (mesh) {
  28606. if (mesh.getClassName() === "LinesMesh") {
  28607. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28608. this.updateExtend();
  28609. }
  28610. this.applyToMesh(mesh);
  28611. mesh.computeWorldMatrix(true);
  28612. }
  28613. }
  28614. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28615. /**
  28616. * 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
  28617. * @returns The Bias Vector
  28618. */
  28619. get: function () {
  28620. return this._boundingBias;
  28621. },
  28622. set: function (value) {
  28623. if (this._boundingBias && this._boundingBias.equals(value)) {
  28624. return;
  28625. }
  28626. this._boundingBias = value.clone();
  28627. this.updateBoundingInfo(true, null);
  28628. },
  28629. enumerable: true,
  28630. configurable: true
  28631. });
  28632. Object.defineProperty(Geometry.prototype, "extend", {
  28633. get: function () {
  28634. return this._extend;
  28635. },
  28636. enumerable: true,
  28637. configurable: true
  28638. });
  28639. Geometry.prototype.getScene = function () {
  28640. return this._scene;
  28641. };
  28642. Geometry.prototype.getEngine = function () {
  28643. return this._engine;
  28644. };
  28645. Geometry.prototype.isReady = function () {
  28646. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28647. };
  28648. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28649. get: function () {
  28650. for (var index = 0; index < this._meshes.length; index++) {
  28651. if (!this._meshes[index].doNotSerialize) {
  28652. return false;
  28653. }
  28654. }
  28655. return true;
  28656. },
  28657. enumerable: true,
  28658. configurable: true
  28659. });
  28660. Geometry.prototype._rebuild = function () {
  28661. if (this._vertexArrayObjects) {
  28662. this._vertexArrayObjects = {};
  28663. }
  28664. // Index buffer
  28665. if (this._meshes.length !== 0 && this._indices) {
  28666. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28667. }
  28668. // Vertex buffers
  28669. for (var key in this._vertexBuffers) {
  28670. var vertexBuffer = this._vertexBuffers[key];
  28671. vertexBuffer._rebuild();
  28672. }
  28673. };
  28674. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28675. vertexData.applyToGeometry(this, updatable);
  28676. this.notifyUpdate();
  28677. };
  28678. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28679. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28680. this.setVerticesBuffer(buffer);
  28681. };
  28682. Geometry.prototype.removeVerticesData = function (kind) {
  28683. if (this._vertexBuffers[kind]) {
  28684. this._vertexBuffers[kind].dispose();
  28685. delete this._vertexBuffers[kind];
  28686. }
  28687. };
  28688. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28689. var kind = buffer.getKind();
  28690. if (this._vertexBuffers[kind]) {
  28691. this._vertexBuffers[kind].dispose();
  28692. }
  28693. this._vertexBuffers[kind] = buffer;
  28694. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28695. var data = buffer.getData();
  28696. var stride = buffer.getStrideSize();
  28697. this._totalVertices = data.length / stride;
  28698. this.updateExtend(data, stride);
  28699. this._resetPointsArrayCache();
  28700. var meshes = this._meshes;
  28701. var numOfMeshes = meshes.length;
  28702. for (var index = 0; index < numOfMeshes; index++) {
  28703. var mesh = meshes[index];
  28704. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28705. mesh._createGlobalSubMesh(false);
  28706. mesh.computeWorldMatrix(true);
  28707. }
  28708. }
  28709. this.notifyUpdate(kind);
  28710. if (this._vertexArrayObjects) {
  28711. this._disposeVertexArrayObjects();
  28712. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28713. }
  28714. };
  28715. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28716. var vertexBuffer = this.getVertexBuffer(kind);
  28717. if (!vertexBuffer) {
  28718. return;
  28719. }
  28720. vertexBuffer.updateDirectly(data, offset);
  28721. this.notifyUpdate(kind);
  28722. };
  28723. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28724. var vertexBuffer = this.getVertexBuffer(kind);
  28725. if (!vertexBuffer) {
  28726. return;
  28727. }
  28728. vertexBuffer.update(data);
  28729. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28730. var stride = vertexBuffer.getStrideSize();
  28731. this._totalVertices = data.length / stride;
  28732. this.updateBoundingInfo(updateExtends, data);
  28733. }
  28734. this.notifyUpdate(kind);
  28735. };
  28736. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28737. if (updateExtends) {
  28738. this.updateExtend(data);
  28739. }
  28740. var meshes = this._meshes;
  28741. var numOfMeshes = meshes.length;
  28742. this._resetPointsArrayCache();
  28743. for (var index = 0; index < numOfMeshes; index++) {
  28744. var mesh = meshes[index];
  28745. if (updateExtends) {
  28746. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28747. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28748. var subMesh = mesh.subMeshes[subIndex];
  28749. subMesh.refreshBoundingInfo();
  28750. }
  28751. }
  28752. }
  28753. };
  28754. Geometry.prototype._bind = function (effect, indexToBind) {
  28755. if (indexToBind === void 0) { indexToBind = undefined; }
  28756. if (indexToBind === undefined) {
  28757. indexToBind = this._indexBuffer;
  28758. }
  28759. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  28760. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  28761. return;
  28762. }
  28763. // Using VAO
  28764. if (!this._vertexArrayObjects[effect.key]) {
  28765. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  28766. }
  28767. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  28768. };
  28769. Geometry.prototype.getTotalVertices = function () {
  28770. if (!this.isReady()) {
  28771. return 0;
  28772. }
  28773. return this._totalVertices;
  28774. };
  28775. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28776. var vertexBuffer = this.getVertexBuffer(kind);
  28777. if (!vertexBuffer) {
  28778. return null;
  28779. }
  28780. var orig = vertexBuffer.getData();
  28781. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  28782. return orig;
  28783. }
  28784. else {
  28785. var len = orig.length;
  28786. var copy = [];
  28787. for (var i = 0; i < len; i++) {
  28788. copy.push(orig[i]);
  28789. }
  28790. return copy;
  28791. }
  28792. };
  28793. Geometry.prototype.getVertexBuffer = function (kind) {
  28794. if (!this.isReady()) {
  28795. return null;
  28796. }
  28797. return this._vertexBuffers[kind];
  28798. };
  28799. Geometry.prototype.getVertexBuffers = function () {
  28800. if (!this.isReady()) {
  28801. return null;
  28802. }
  28803. return this._vertexBuffers;
  28804. };
  28805. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28806. if (!this._vertexBuffers) {
  28807. if (this._delayInfo) {
  28808. return this._delayInfo.indexOf(kind) !== -1;
  28809. }
  28810. return false;
  28811. }
  28812. return this._vertexBuffers[kind] !== undefined;
  28813. };
  28814. Geometry.prototype.getVerticesDataKinds = function () {
  28815. var result = [];
  28816. var kind;
  28817. if (!this._vertexBuffers && this._delayInfo) {
  28818. for (kind in this._delayInfo) {
  28819. result.push(kind);
  28820. }
  28821. }
  28822. else {
  28823. for (kind in this._vertexBuffers) {
  28824. result.push(kind);
  28825. }
  28826. }
  28827. return result;
  28828. };
  28829. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28830. if (this._indexBuffer) {
  28831. this._engine._releaseBuffer(this._indexBuffer);
  28832. }
  28833. this._disposeVertexArrayObjects();
  28834. this._indices = indices;
  28835. if (this._meshes.length !== 0 && this._indices) {
  28836. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28837. }
  28838. if (totalVertices !== undefined) {
  28839. this._totalVertices = totalVertices;
  28840. }
  28841. var meshes = this._meshes;
  28842. var numOfMeshes = meshes.length;
  28843. for (var index = 0; index < numOfMeshes; index++) {
  28844. meshes[index]._createGlobalSubMesh(true);
  28845. }
  28846. this.notifyUpdate();
  28847. };
  28848. Geometry.prototype.getTotalIndices = function () {
  28849. if (!this.isReady()) {
  28850. return 0;
  28851. }
  28852. return this._indices.length;
  28853. };
  28854. Geometry.prototype.getIndices = function (copyWhenShared) {
  28855. if (!this.isReady()) {
  28856. return null;
  28857. }
  28858. var orig = this._indices;
  28859. if (!copyWhenShared || this._meshes.length === 1) {
  28860. return orig;
  28861. }
  28862. else {
  28863. var len = orig.length;
  28864. var copy = [];
  28865. for (var i = 0; i < len; i++) {
  28866. copy.push(orig[i]);
  28867. }
  28868. return copy;
  28869. }
  28870. };
  28871. Geometry.prototype.getIndexBuffer = function () {
  28872. if (!this.isReady()) {
  28873. return null;
  28874. }
  28875. return this._indexBuffer;
  28876. };
  28877. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  28878. if (!effect || !this._vertexArrayObjects) {
  28879. return;
  28880. }
  28881. if (this._vertexArrayObjects[effect.key]) {
  28882. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  28883. delete this._vertexArrayObjects[effect.key];
  28884. }
  28885. };
  28886. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28887. var meshes = this._meshes;
  28888. var index = meshes.indexOf(mesh);
  28889. if (index === -1) {
  28890. return;
  28891. }
  28892. meshes.splice(index, 1);
  28893. mesh._geometry = null;
  28894. if (meshes.length === 0 && shouldDispose) {
  28895. this.dispose();
  28896. }
  28897. };
  28898. Geometry.prototype.applyToMesh = function (mesh) {
  28899. if (mesh._geometry === this) {
  28900. return;
  28901. }
  28902. var previousGeometry = mesh._geometry;
  28903. if (previousGeometry) {
  28904. previousGeometry.releaseForMesh(mesh);
  28905. }
  28906. var meshes = this._meshes;
  28907. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28908. mesh._geometry = this;
  28909. this._scene.pushGeometry(this);
  28910. meshes.push(mesh);
  28911. if (this.isReady()) {
  28912. this._applyToMesh(mesh);
  28913. }
  28914. else {
  28915. mesh._boundingInfo = this._boundingInfo;
  28916. }
  28917. };
  28918. Geometry.prototype.updateExtend = function (data, stride) {
  28919. if (data === void 0) { data = null; }
  28920. if (!data) {
  28921. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  28922. }
  28923. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  28924. };
  28925. Geometry.prototype._applyToMesh = function (mesh) {
  28926. var numOfMeshes = this._meshes.length;
  28927. // vertexBuffers
  28928. for (var kind in this._vertexBuffers) {
  28929. if (numOfMeshes === 1) {
  28930. this._vertexBuffers[kind].create();
  28931. }
  28932. var buffer = this._vertexBuffers[kind].getBuffer();
  28933. if (buffer)
  28934. buffer.references = numOfMeshes;
  28935. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28936. if (!this._extend) {
  28937. this.updateExtend(this._vertexBuffers[kind].getData());
  28938. }
  28939. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28940. mesh._createGlobalSubMesh(false);
  28941. //bounding info was just created again, world matrix should be applied again.
  28942. mesh._updateBoundingInfo();
  28943. }
  28944. }
  28945. // indexBuffer
  28946. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  28947. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28948. }
  28949. if (this._indexBuffer) {
  28950. this._indexBuffer.references = numOfMeshes;
  28951. }
  28952. };
  28953. Geometry.prototype.notifyUpdate = function (kind) {
  28954. if (this.onGeometryUpdated) {
  28955. this.onGeometryUpdated(this, kind);
  28956. }
  28957. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  28958. var mesh = _a[_i];
  28959. mesh._markSubMeshesAsAttributesDirty();
  28960. }
  28961. };
  28962. Geometry.prototype.load = function (scene, onLoaded) {
  28963. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28964. return;
  28965. }
  28966. if (this.isReady()) {
  28967. if (onLoaded) {
  28968. onLoaded();
  28969. }
  28970. return;
  28971. }
  28972. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28973. this._queueLoad(scene, onLoaded);
  28974. };
  28975. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  28976. var _this = this;
  28977. scene._addPendingData(this);
  28978. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28979. _this._delayLoadingFunction(JSON.parse(data), _this);
  28980. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28981. _this._delayInfo = [];
  28982. scene._removePendingData(_this);
  28983. var meshes = _this._meshes;
  28984. var numOfMeshes = meshes.length;
  28985. for (var index = 0; index < numOfMeshes; index++) {
  28986. _this._applyToMesh(meshes[index]);
  28987. }
  28988. if (onLoaded) {
  28989. onLoaded();
  28990. }
  28991. }, function () { }, scene.database);
  28992. };
  28993. /**
  28994. * Invert the geometry to move from a right handed system to a left handed one.
  28995. */
  28996. Geometry.prototype.toLeftHanded = function () {
  28997. // Flip faces
  28998. var tIndices = this.getIndices(false);
  28999. if (tIndices != null && tIndices.length > 0) {
  29000. for (var i = 0; i < tIndices.length; i += 3) {
  29001. var tTemp = tIndices[i + 0];
  29002. tIndices[i + 0] = tIndices[i + 2];
  29003. tIndices[i + 2] = tTemp;
  29004. }
  29005. this.setIndices(tIndices);
  29006. }
  29007. // Negate position.z
  29008. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  29009. if (tPositions != null && tPositions.length > 0) {
  29010. for (var i = 0; i < tPositions.length; i += 3) {
  29011. tPositions[i + 2] = -tPositions[i + 2];
  29012. }
  29013. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  29014. }
  29015. // Negate normal.z
  29016. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  29017. if (tNormals != null && tNormals.length > 0) {
  29018. for (var i = 0; i < tNormals.length; i += 3) {
  29019. tNormals[i + 2] = -tNormals[i + 2];
  29020. }
  29021. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  29022. }
  29023. };
  29024. // Cache
  29025. Geometry.prototype._resetPointsArrayCache = function () {
  29026. this._positions = null;
  29027. };
  29028. Geometry.prototype._generatePointsArray = function () {
  29029. if (this._positions)
  29030. return true;
  29031. this._positions = [];
  29032. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29033. if (!data) {
  29034. return false;
  29035. }
  29036. for (var index = 0; index < data.length; index += 3) {
  29037. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  29038. }
  29039. return true;
  29040. };
  29041. Geometry.prototype.isDisposed = function () {
  29042. return this._isDisposed;
  29043. };
  29044. Geometry.prototype._disposeVertexArrayObjects = function () {
  29045. if (this._vertexArrayObjects) {
  29046. for (var kind in this._vertexArrayObjects) {
  29047. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  29048. }
  29049. this._vertexArrayObjects = {};
  29050. }
  29051. };
  29052. Geometry.prototype.dispose = function () {
  29053. var meshes = this._meshes;
  29054. var numOfMeshes = meshes.length;
  29055. var index;
  29056. for (index = 0; index < numOfMeshes; index++) {
  29057. this.releaseForMesh(meshes[index]);
  29058. }
  29059. this._meshes = [];
  29060. this._disposeVertexArrayObjects();
  29061. for (var kind in this._vertexBuffers) {
  29062. this._vertexBuffers[kind].dispose();
  29063. }
  29064. this._vertexBuffers = {};
  29065. this._totalVertices = 0;
  29066. if (this._indexBuffer) {
  29067. this._engine._releaseBuffer(this._indexBuffer);
  29068. }
  29069. this._indexBuffer = null;
  29070. this._indices = [];
  29071. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29072. this.delayLoadingFile = null;
  29073. this._delayLoadingFunction = null;
  29074. this._delayInfo = [];
  29075. this._boundingInfo = null;
  29076. this._scene.removeGeometry(this);
  29077. this._isDisposed = true;
  29078. };
  29079. Geometry.prototype.copy = function (id) {
  29080. var vertexData = new BABYLON.VertexData();
  29081. vertexData.indices = [];
  29082. var indices = this.getIndices();
  29083. for (var index = 0; index < indices.length; index++) {
  29084. vertexData.indices.push(indices[index]);
  29085. }
  29086. var updatable = false;
  29087. var stopChecking = false;
  29088. var kind;
  29089. for (kind in this._vertexBuffers) {
  29090. // using slice() to make a copy of the array and not just reference it
  29091. var data = this.getVerticesData(kind);
  29092. if (data instanceof Float32Array) {
  29093. vertexData.set(new Float32Array(data), kind);
  29094. }
  29095. else {
  29096. vertexData.set(data.slice(0), kind);
  29097. }
  29098. if (!stopChecking) {
  29099. updatable = this.getVertexBuffer(kind).isUpdatable();
  29100. stopChecking = !updatable;
  29101. }
  29102. }
  29103. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29104. geometry.delayLoadState = this.delayLoadState;
  29105. geometry.delayLoadingFile = this.delayLoadingFile;
  29106. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29107. for (kind in this._delayInfo) {
  29108. geometry._delayInfo = geometry._delayInfo || [];
  29109. geometry._delayInfo.push(kind);
  29110. }
  29111. // Bounding info
  29112. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29113. return geometry;
  29114. };
  29115. Geometry.prototype.serialize = function () {
  29116. var serializationObject = {};
  29117. serializationObject.id = this.id;
  29118. serializationObject.updatable = this._updatable;
  29119. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29120. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29121. }
  29122. return serializationObject;
  29123. };
  29124. Geometry.prototype.toNumberArray = function (origin) {
  29125. if (Array.isArray(origin)) {
  29126. return origin;
  29127. }
  29128. else {
  29129. return Array.prototype.slice.call(origin);
  29130. }
  29131. };
  29132. Geometry.prototype.serializeVerticeData = function () {
  29133. var serializationObject = this.serialize();
  29134. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29135. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  29136. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  29137. serializationObject.positions._updatable = true;
  29138. }
  29139. }
  29140. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29141. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  29142. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  29143. serializationObject.normals._updatable = true;
  29144. }
  29145. }
  29146. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29147. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  29148. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  29149. serializationObject.uvs._updatable = true;
  29150. }
  29151. }
  29152. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29153. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  29154. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  29155. serializationObject.uv2s._updatable = true;
  29156. }
  29157. }
  29158. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29159. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  29160. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  29161. serializationObject.uv3s._updatable = true;
  29162. }
  29163. }
  29164. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29165. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  29166. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  29167. serializationObject.uv4s._updatable = true;
  29168. }
  29169. }
  29170. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29171. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  29172. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  29173. serializationObject.uv5s._updatable = true;
  29174. }
  29175. }
  29176. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29177. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29178. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29179. serializationObject.uv6s._updatable = true;
  29180. }
  29181. }
  29182. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29183. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29184. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29185. serializationObject.colors._updatable = true;
  29186. }
  29187. }
  29188. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29189. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29190. serializationObject.matricesIndices._isExpanded = true;
  29191. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29192. serializationObject.matricesIndices._updatable = true;
  29193. }
  29194. }
  29195. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29196. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29197. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29198. serializationObject.matricesWeights._updatable = true;
  29199. }
  29200. }
  29201. serializationObject.indices = this.toNumberArray(this.getIndices());
  29202. return serializationObject;
  29203. };
  29204. // Statics
  29205. Geometry.ExtractFromMesh = function (mesh, id) {
  29206. var geometry = mesh._geometry;
  29207. if (!geometry) {
  29208. return null;
  29209. }
  29210. return geometry.copy(id);
  29211. };
  29212. /**
  29213. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29214. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29215. * Be aware Math.random() could cause collisions, but:
  29216. * "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"
  29217. */
  29218. Geometry.RandomId = function () {
  29219. return BABYLON.Tools.RandomId();
  29220. };
  29221. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29222. var scene = mesh.getScene();
  29223. // Geometry
  29224. var geometryId = parsedGeometry.geometryId;
  29225. if (geometryId) {
  29226. var geometry = scene.getGeometryByID(geometryId);
  29227. if (geometry) {
  29228. geometry.applyToMesh(mesh);
  29229. }
  29230. }
  29231. else if (parsedGeometry instanceof ArrayBuffer) {
  29232. var binaryInfo = mesh._binaryInfo;
  29233. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29234. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29235. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29236. }
  29237. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29238. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29239. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29240. }
  29241. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29242. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29243. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29244. }
  29245. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29246. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29247. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29248. }
  29249. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29250. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29251. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29252. }
  29253. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29254. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29255. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29256. }
  29257. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29258. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29259. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29260. }
  29261. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29262. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29263. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29264. }
  29265. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29266. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29267. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29268. }
  29269. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29270. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29271. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29272. }
  29273. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29274. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29275. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29276. }
  29277. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29278. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29279. mesh.setIndices(indicesData);
  29280. }
  29281. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29282. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29283. mesh.subMeshes = [];
  29284. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29285. var materialIndex = subMeshesData[(i * 5) + 0];
  29286. var verticesStart = subMeshesData[(i * 5) + 1];
  29287. var verticesCount = subMeshesData[(i * 5) + 2];
  29288. var indexStart = subMeshesData[(i * 5) + 3];
  29289. var indexCount = subMeshesData[(i * 5) + 4];
  29290. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29291. }
  29292. }
  29293. }
  29294. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29295. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29296. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29297. if (parsedGeometry.uvs) {
  29298. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29299. }
  29300. if (parsedGeometry.uvs2) {
  29301. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29302. }
  29303. if (parsedGeometry.uvs3) {
  29304. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29305. }
  29306. if (parsedGeometry.uvs4) {
  29307. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29308. }
  29309. if (parsedGeometry.uvs5) {
  29310. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29311. }
  29312. if (parsedGeometry.uvs6) {
  29313. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29314. }
  29315. if (parsedGeometry.colors) {
  29316. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29317. }
  29318. if (parsedGeometry.matricesIndices) {
  29319. if (!parsedGeometry.matricesIndices._isExpanded) {
  29320. var floatIndices = [];
  29321. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29322. var matricesIndex = parsedGeometry.matricesIndices[i];
  29323. floatIndices.push(matricesIndex & 0x000000FF);
  29324. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29325. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29326. floatIndices.push(matricesIndex >> 24);
  29327. }
  29328. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29329. }
  29330. else {
  29331. delete parsedGeometry.matricesIndices._isExpanded;
  29332. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29333. }
  29334. }
  29335. if (parsedGeometry.matricesIndicesExtra) {
  29336. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29337. var floatIndices = [];
  29338. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29339. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29340. floatIndices.push(matricesIndex & 0x000000FF);
  29341. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29342. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29343. floatIndices.push(matricesIndex >> 24);
  29344. }
  29345. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29346. }
  29347. else {
  29348. delete parsedGeometry.matricesIndices._isExpanded;
  29349. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29350. }
  29351. }
  29352. if (parsedGeometry.matricesWeights) {
  29353. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  29354. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29355. }
  29356. if (parsedGeometry.matricesWeightsExtra) {
  29357. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  29358. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29359. }
  29360. mesh.setIndices(parsedGeometry.indices);
  29361. }
  29362. // SubMeshes
  29363. if (parsedGeometry.subMeshes) {
  29364. mesh.subMeshes = [];
  29365. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29366. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29367. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29368. }
  29369. }
  29370. // Flat shading
  29371. if (mesh._shouldGenerateFlatShading) {
  29372. mesh.convertToFlatShadedMesh();
  29373. delete mesh._shouldGenerateFlatShading;
  29374. }
  29375. // Update
  29376. mesh.computeWorldMatrix(true);
  29377. // Octree
  29378. if (scene['_selectionOctree']) {
  29379. scene['_selectionOctree'].addMesh(mesh);
  29380. }
  29381. };
  29382. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  29383. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29384. return;
  29385. }
  29386. var size = matricesWeights.length;
  29387. for (var i = 0; i < size; i += influencers) {
  29388. var weight = 0;
  29389. var biggerIndex = i;
  29390. var biggerWeight = 0;
  29391. for (var j = 0; j < influencers - 1; j++) {
  29392. weight += matricesWeights[i + j];
  29393. if (matricesWeights[i + j] > biggerWeight) {
  29394. biggerWeight = matricesWeights[i + j];
  29395. biggerIndex = i + j;
  29396. }
  29397. }
  29398. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  29399. }
  29400. };
  29401. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29402. if (scene.getGeometryByID(parsedVertexData.id)) {
  29403. return null; // null since geometry could be something else than a box...
  29404. }
  29405. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29406. if (BABYLON.Tags) {
  29407. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29408. }
  29409. if (parsedVertexData.delayLoadingFile) {
  29410. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29411. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29412. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29413. geometry._delayInfo = [];
  29414. if (parsedVertexData.hasUVs) {
  29415. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29416. }
  29417. if (parsedVertexData.hasUVs2) {
  29418. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29419. }
  29420. if (parsedVertexData.hasUVs3) {
  29421. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29422. }
  29423. if (parsedVertexData.hasUVs4) {
  29424. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29425. }
  29426. if (parsedVertexData.hasUVs5) {
  29427. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29428. }
  29429. if (parsedVertexData.hasUVs6) {
  29430. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29431. }
  29432. if (parsedVertexData.hasColors) {
  29433. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29434. }
  29435. if (parsedVertexData.hasMatricesIndices) {
  29436. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29437. }
  29438. if (parsedVertexData.hasMatricesWeights) {
  29439. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29440. }
  29441. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29442. }
  29443. else {
  29444. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29445. }
  29446. scene.pushGeometry(geometry, true);
  29447. return geometry;
  29448. };
  29449. return Geometry;
  29450. }());
  29451. BABYLON.Geometry = Geometry;
  29452. /////// Primitives //////////////////////////////////////////////
  29453. (function (Geometry) {
  29454. var Primitives;
  29455. (function (Primitives) {
  29456. /// Abstract class
  29457. var _Primitive = (function (_super) {
  29458. __extends(_Primitive, _super);
  29459. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29460. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29461. _this._canBeRegenerated = _canBeRegenerated;
  29462. _this._beingRegenerated = true;
  29463. _this.regenerate();
  29464. _this._beingRegenerated = false;
  29465. return _this;
  29466. }
  29467. _Primitive.prototype.canBeRegenerated = function () {
  29468. return this._canBeRegenerated;
  29469. };
  29470. _Primitive.prototype.regenerate = function () {
  29471. if (!this._canBeRegenerated) {
  29472. return;
  29473. }
  29474. this._beingRegenerated = true;
  29475. this.setAllVerticesData(this._regenerateVertexData(), false);
  29476. this._beingRegenerated = false;
  29477. };
  29478. _Primitive.prototype.asNewGeometry = function (id) {
  29479. return _super.prototype.copy.call(this, id);
  29480. };
  29481. // overrides
  29482. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29483. if (!this._beingRegenerated) {
  29484. return;
  29485. }
  29486. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29487. };
  29488. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29489. if (!this._beingRegenerated) {
  29490. return;
  29491. }
  29492. _super.prototype.setVerticesData.call(this, kind, data, false);
  29493. };
  29494. // to override
  29495. // protected
  29496. _Primitive.prototype._regenerateVertexData = function () {
  29497. throw new Error("Abstract method");
  29498. };
  29499. _Primitive.prototype.copy = function (id) {
  29500. throw new Error("Must be overriden in sub-classes.");
  29501. };
  29502. _Primitive.prototype.serialize = function () {
  29503. var serializationObject = _super.prototype.serialize.call(this);
  29504. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29505. return serializationObject;
  29506. };
  29507. return _Primitive;
  29508. }(Geometry));
  29509. Primitives._Primitive = _Primitive;
  29510. var Ribbon = (function (_super) {
  29511. __extends(Ribbon, _super);
  29512. // Members
  29513. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29514. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29515. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29516. _this.pathArray = pathArray;
  29517. _this.closeArray = closeArray;
  29518. _this.closePath = closePath;
  29519. _this.offset = offset;
  29520. _this.side = side;
  29521. return _this;
  29522. }
  29523. Ribbon.prototype._regenerateVertexData = function () {
  29524. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29525. };
  29526. Ribbon.prototype.copy = function (id) {
  29527. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29528. };
  29529. return Ribbon;
  29530. }(_Primitive));
  29531. Primitives.Ribbon = Ribbon;
  29532. var Box = (function (_super) {
  29533. __extends(Box, _super);
  29534. // Members
  29535. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29536. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29537. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29538. _this.size = size;
  29539. _this.side = side;
  29540. return _this;
  29541. }
  29542. Box.prototype._regenerateVertexData = function () {
  29543. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29544. };
  29545. Box.prototype.copy = function (id) {
  29546. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29547. };
  29548. Box.prototype.serialize = function () {
  29549. var serializationObject = _super.prototype.serialize.call(this);
  29550. serializationObject.size = this.size;
  29551. return serializationObject;
  29552. };
  29553. Box.Parse = function (parsedBox, scene) {
  29554. if (scene.getGeometryByID(parsedBox.id)) {
  29555. return null; // null since geometry could be something else than a box...
  29556. }
  29557. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29558. if (BABYLON.Tags) {
  29559. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  29560. }
  29561. scene.pushGeometry(box, true);
  29562. return box;
  29563. };
  29564. return Box;
  29565. }(_Primitive));
  29566. Primitives.Box = Box;
  29567. var Sphere = (function (_super) {
  29568. __extends(Sphere, _super);
  29569. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29570. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29571. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29572. _this.segments = segments;
  29573. _this.diameter = diameter;
  29574. _this.side = side;
  29575. return _this;
  29576. }
  29577. Sphere.prototype._regenerateVertexData = function () {
  29578. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29579. };
  29580. Sphere.prototype.copy = function (id) {
  29581. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29582. };
  29583. Sphere.prototype.serialize = function () {
  29584. var serializationObject = _super.prototype.serialize.call(this);
  29585. serializationObject.segments = this.segments;
  29586. serializationObject.diameter = this.diameter;
  29587. return serializationObject;
  29588. };
  29589. Sphere.Parse = function (parsedSphere, scene) {
  29590. if (scene.getGeometryByID(parsedSphere.id)) {
  29591. return null; // null since geometry could be something else than a sphere...
  29592. }
  29593. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29594. if (BABYLON.Tags) {
  29595. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29596. }
  29597. scene.pushGeometry(sphere, true);
  29598. return sphere;
  29599. };
  29600. return Sphere;
  29601. }(_Primitive));
  29602. Primitives.Sphere = Sphere;
  29603. var Disc = (function (_super) {
  29604. __extends(Disc, _super);
  29605. // Members
  29606. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29607. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29608. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29609. _this.radius = radius;
  29610. _this.tessellation = tessellation;
  29611. _this.side = side;
  29612. return _this;
  29613. }
  29614. Disc.prototype._regenerateVertexData = function () {
  29615. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29616. };
  29617. Disc.prototype.copy = function (id) {
  29618. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29619. };
  29620. return Disc;
  29621. }(_Primitive));
  29622. Primitives.Disc = Disc;
  29623. var Cylinder = (function (_super) {
  29624. __extends(Cylinder, _super);
  29625. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29626. if (subdivisions === void 0) { subdivisions = 1; }
  29627. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29628. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29629. _this.height = height;
  29630. _this.diameterTop = diameterTop;
  29631. _this.diameterBottom = diameterBottom;
  29632. _this.tessellation = tessellation;
  29633. _this.subdivisions = subdivisions;
  29634. _this.side = side;
  29635. return _this;
  29636. }
  29637. Cylinder.prototype._regenerateVertexData = function () {
  29638. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29639. };
  29640. Cylinder.prototype.copy = function (id) {
  29641. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29642. };
  29643. Cylinder.prototype.serialize = function () {
  29644. var serializationObject = _super.prototype.serialize.call(this);
  29645. serializationObject.height = this.height;
  29646. serializationObject.diameterTop = this.diameterTop;
  29647. serializationObject.diameterBottom = this.diameterBottom;
  29648. serializationObject.tessellation = this.tessellation;
  29649. return serializationObject;
  29650. };
  29651. Cylinder.Parse = function (parsedCylinder, scene) {
  29652. if (scene.getGeometryByID(parsedCylinder.id)) {
  29653. return null; // null since geometry could be something else than a cylinder...
  29654. }
  29655. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29656. if (BABYLON.Tags) {
  29657. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29658. }
  29659. scene.pushGeometry(cylinder, true);
  29660. return cylinder;
  29661. };
  29662. return Cylinder;
  29663. }(_Primitive));
  29664. Primitives.Cylinder = Cylinder;
  29665. var Torus = (function (_super) {
  29666. __extends(Torus, _super);
  29667. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29668. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29669. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29670. _this.diameter = diameter;
  29671. _this.thickness = thickness;
  29672. _this.tessellation = tessellation;
  29673. _this.side = side;
  29674. return _this;
  29675. }
  29676. Torus.prototype._regenerateVertexData = function () {
  29677. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29678. };
  29679. Torus.prototype.copy = function (id) {
  29680. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29681. };
  29682. Torus.prototype.serialize = function () {
  29683. var serializationObject = _super.prototype.serialize.call(this);
  29684. serializationObject.diameter = this.diameter;
  29685. serializationObject.thickness = this.thickness;
  29686. serializationObject.tessellation = this.tessellation;
  29687. return serializationObject;
  29688. };
  29689. Torus.Parse = function (parsedTorus, scene) {
  29690. if (scene.getGeometryByID(parsedTorus.id)) {
  29691. return null; // null since geometry could be something else than a torus...
  29692. }
  29693. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29694. if (BABYLON.Tags) {
  29695. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29696. }
  29697. scene.pushGeometry(torus, true);
  29698. return torus;
  29699. };
  29700. return Torus;
  29701. }(_Primitive));
  29702. Primitives.Torus = Torus;
  29703. var Ground = (function (_super) {
  29704. __extends(Ground, _super);
  29705. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29706. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29707. _this.width = width;
  29708. _this.height = height;
  29709. _this.subdivisions = subdivisions;
  29710. return _this;
  29711. }
  29712. Ground.prototype._regenerateVertexData = function () {
  29713. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29714. };
  29715. Ground.prototype.copy = function (id) {
  29716. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29717. };
  29718. Ground.prototype.serialize = function () {
  29719. var serializationObject = _super.prototype.serialize.call(this);
  29720. serializationObject.width = this.width;
  29721. serializationObject.height = this.height;
  29722. serializationObject.subdivisions = this.subdivisions;
  29723. return serializationObject;
  29724. };
  29725. Ground.Parse = function (parsedGround, scene) {
  29726. if (scene.getGeometryByID(parsedGround.id)) {
  29727. return null; // null since geometry could be something else than a ground...
  29728. }
  29729. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29730. if (BABYLON.Tags) {
  29731. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29732. }
  29733. scene.pushGeometry(ground, true);
  29734. return ground;
  29735. };
  29736. return Ground;
  29737. }(_Primitive));
  29738. Primitives.Ground = Ground;
  29739. var TiledGround = (function (_super) {
  29740. __extends(TiledGround, _super);
  29741. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29742. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29743. _this.xmin = xmin;
  29744. _this.zmin = zmin;
  29745. _this.xmax = xmax;
  29746. _this.zmax = zmax;
  29747. _this.subdivisions = subdivisions;
  29748. _this.precision = precision;
  29749. return _this;
  29750. }
  29751. TiledGround.prototype._regenerateVertexData = function () {
  29752. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29753. };
  29754. TiledGround.prototype.copy = function (id) {
  29755. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29756. };
  29757. return TiledGround;
  29758. }(_Primitive));
  29759. Primitives.TiledGround = TiledGround;
  29760. var Plane = (function (_super) {
  29761. __extends(Plane, _super);
  29762. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29763. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29764. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29765. _this.size = size;
  29766. _this.side = side;
  29767. return _this;
  29768. }
  29769. Plane.prototype._regenerateVertexData = function () {
  29770. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29771. };
  29772. Plane.prototype.copy = function (id) {
  29773. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29774. };
  29775. Plane.prototype.serialize = function () {
  29776. var serializationObject = _super.prototype.serialize.call(this);
  29777. serializationObject.size = this.size;
  29778. return serializationObject;
  29779. };
  29780. Plane.Parse = function (parsedPlane, scene) {
  29781. if (scene.getGeometryByID(parsedPlane.id)) {
  29782. return null; // null since geometry could be something else than a ground...
  29783. }
  29784. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  29785. if (BABYLON.Tags) {
  29786. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  29787. }
  29788. scene.pushGeometry(plane, true);
  29789. return plane;
  29790. };
  29791. return Plane;
  29792. }(_Primitive));
  29793. Primitives.Plane = Plane;
  29794. var TorusKnot = (function (_super) {
  29795. __extends(TorusKnot, _super);
  29796. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29797. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29798. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29799. _this.radius = radius;
  29800. _this.tube = tube;
  29801. _this.radialSegments = radialSegments;
  29802. _this.tubularSegments = tubularSegments;
  29803. _this.p = p;
  29804. _this.q = q;
  29805. _this.side = side;
  29806. return _this;
  29807. }
  29808. TorusKnot.prototype._regenerateVertexData = function () {
  29809. 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 });
  29810. };
  29811. TorusKnot.prototype.copy = function (id) {
  29812. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29813. };
  29814. TorusKnot.prototype.serialize = function () {
  29815. var serializationObject = _super.prototype.serialize.call(this);
  29816. serializationObject.radius = this.radius;
  29817. serializationObject.tube = this.tube;
  29818. serializationObject.radialSegments = this.radialSegments;
  29819. serializationObject.tubularSegments = this.tubularSegments;
  29820. serializationObject.p = this.p;
  29821. serializationObject.q = this.q;
  29822. return serializationObject;
  29823. };
  29824. ;
  29825. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  29826. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  29827. return null; // null since geometry could be something else than a ground...
  29828. }
  29829. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  29830. if (BABYLON.Tags) {
  29831. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  29832. }
  29833. scene.pushGeometry(torusKnot, true);
  29834. return torusKnot;
  29835. };
  29836. return TorusKnot;
  29837. }(_Primitive));
  29838. Primitives.TorusKnot = TorusKnot;
  29839. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29840. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29841. })(BABYLON || (BABYLON = {}));
  29842. //# sourceMappingURL=babylon.geometry.js.map
  29843. var BABYLON;
  29844. (function (BABYLON) {
  29845. var PostProcessManager = (function () {
  29846. function PostProcessManager(scene) {
  29847. this._vertexBuffers = {};
  29848. this._scene = scene;
  29849. }
  29850. PostProcessManager.prototype._prepareBuffers = function () {
  29851. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29852. return;
  29853. }
  29854. // VBO
  29855. var vertices = [];
  29856. vertices.push(1, 1);
  29857. vertices.push(-1, 1);
  29858. vertices.push(-1, -1);
  29859. vertices.push(1, -1);
  29860. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29861. this._buildIndexBuffer();
  29862. };
  29863. PostProcessManager.prototype._buildIndexBuffer = function () {
  29864. // Indices
  29865. var indices = [];
  29866. indices.push(0);
  29867. indices.push(1);
  29868. indices.push(2);
  29869. indices.push(0);
  29870. indices.push(2);
  29871. indices.push(3);
  29872. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29873. };
  29874. PostProcessManager.prototype._rebuild = function () {
  29875. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29876. return;
  29877. }
  29878. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  29879. this._buildIndexBuffer();
  29880. };
  29881. // Methods
  29882. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  29883. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29884. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29885. return false;
  29886. }
  29887. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  29888. return true;
  29889. };
  29890. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  29891. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  29892. var engine = this._scene.getEngine();
  29893. for (var index = 0; index < postProcesses.length; index++) {
  29894. if (index < postProcesses.length - 1) {
  29895. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29896. }
  29897. else {
  29898. if (targetTexture) {
  29899. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  29900. }
  29901. else {
  29902. engine.restoreDefaultFramebuffer();
  29903. }
  29904. }
  29905. var pp = postProcesses[index];
  29906. var effect = pp.apply();
  29907. if (effect) {
  29908. pp.onBeforeRenderObservable.notifyObservers(effect);
  29909. // VBOs
  29910. this._prepareBuffers();
  29911. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29912. // Draw order
  29913. engine.draw(true, 0, 6);
  29914. pp.onAfterRenderObservable.notifyObservers(effect);
  29915. }
  29916. }
  29917. // Restore depth buffer
  29918. engine.setDepthBuffer(true);
  29919. engine.setDepthWrite(true);
  29920. };
  29921. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29922. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29923. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29924. return;
  29925. }
  29926. var engine = this._scene.getEngine();
  29927. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29928. if (index < len - 1) {
  29929. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29930. }
  29931. else {
  29932. if (targetTexture) {
  29933. engine.bindFramebuffer(targetTexture, faceIndex);
  29934. }
  29935. else {
  29936. engine.restoreDefaultFramebuffer();
  29937. }
  29938. }
  29939. if (doNotPresent) {
  29940. break;
  29941. }
  29942. var pp = postProcesses[index];
  29943. var effect = pp.apply();
  29944. if (effect) {
  29945. pp.onBeforeRenderObservable.notifyObservers(effect);
  29946. // VBOs
  29947. this._prepareBuffers();
  29948. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29949. // Draw order
  29950. engine.draw(true, 0, 6);
  29951. pp.onAfterRenderObservable.notifyObservers(effect);
  29952. }
  29953. }
  29954. // Restore states
  29955. engine.setDepthBuffer(true);
  29956. engine.setDepthWrite(true);
  29957. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29958. };
  29959. PostProcessManager.prototype.dispose = function () {
  29960. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29961. if (buffer) {
  29962. buffer.dispose();
  29963. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29964. }
  29965. if (this._indexBuffer) {
  29966. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29967. this._indexBuffer = null;
  29968. }
  29969. };
  29970. return PostProcessManager;
  29971. }());
  29972. BABYLON.PostProcessManager = PostProcessManager;
  29973. })(BABYLON || (BABYLON = {}));
  29974. //# sourceMappingURL=babylon.postProcessManager.js.map
  29975. var BABYLON;
  29976. (function (BABYLON) {
  29977. /**
  29978. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  29979. */
  29980. var PerformanceMonitor = (function () {
  29981. /**
  29982. * constructor
  29983. * @param frameSampleSize The number of samples required to saturate the sliding window
  29984. */
  29985. function PerformanceMonitor(frameSampleSize) {
  29986. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  29987. this._enabled = true;
  29988. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  29989. }
  29990. /**
  29991. * Samples current frame
  29992. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  29993. */
  29994. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  29995. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  29996. if (!this._enabled)
  29997. return;
  29998. if (this._lastFrameTimeMs != null) {
  29999. var dt = timeMs - this._lastFrameTimeMs;
  30000. this._rollingFrameTime.add(dt);
  30001. }
  30002. this._lastFrameTimeMs = timeMs;
  30003. };
  30004. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  30005. /**
  30006. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30007. * @return Average frame time in milliseconds
  30008. */
  30009. get: function () {
  30010. return this._rollingFrameTime.average;
  30011. },
  30012. enumerable: true,
  30013. configurable: true
  30014. });
  30015. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  30016. /**
  30017. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30018. * @return Frame time variance in milliseconds squared
  30019. */
  30020. get: function () {
  30021. return this._rollingFrameTime.variance;
  30022. },
  30023. enumerable: true,
  30024. configurable: true
  30025. });
  30026. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  30027. /**
  30028. * Returns the frame time of the most recent frame
  30029. * @return Frame time in milliseconds
  30030. */
  30031. get: function () {
  30032. return this._rollingFrameTime.history(0);
  30033. },
  30034. enumerable: true,
  30035. configurable: true
  30036. });
  30037. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  30038. /**
  30039. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  30040. * @return Framerate in frames per second
  30041. */
  30042. get: function () {
  30043. return 1000.0 / this._rollingFrameTime.average;
  30044. },
  30045. enumerable: true,
  30046. configurable: true
  30047. });
  30048. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  30049. /**
  30050. * Returns the average framerate in frames per second using the most recent frame time
  30051. * @return Framerate in frames per second
  30052. */
  30053. get: function () {
  30054. return 1000.0 / this._rollingFrameTime.history(0);
  30055. },
  30056. enumerable: true,
  30057. configurable: true
  30058. });
  30059. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  30060. /**
  30061. * Returns true if enough samples have been taken to completely fill the sliding window
  30062. * @return true if saturated
  30063. */
  30064. get: function () {
  30065. return this._rollingFrameTime.isSaturated();
  30066. },
  30067. enumerable: true,
  30068. configurable: true
  30069. });
  30070. /**
  30071. * Enables contributions to the sliding window sample set
  30072. */
  30073. PerformanceMonitor.prototype.enable = function () {
  30074. this._enabled = true;
  30075. };
  30076. /**
  30077. * Disables contributions to the sliding window sample set
  30078. * Samples will not be interpolated over the disabled period
  30079. */
  30080. PerformanceMonitor.prototype.disable = function () {
  30081. this._enabled = false;
  30082. //clear last sample to avoid interpolating over the disabled period when next enabled
  30083. this._lastFrameTimeMs = null;
  30084. this._lastChangeTimeMs = null;
  30085. };
  30086. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  30087. /**
  30088. * Returns true if sampling is enabled
  30089. * @return true if enabled
  30090. */
  30091. get: function () {
  30092. return this._enabled;
  30093. },
  30094. enumerable: true,
  30095. configurable: true
  30096. });
  30097. /**
  30098. * Resets performance monitor
  30099. */
  30100. PerformanceMonitor.prototype.reset = function () {
  30101. //clear last sample to avoid interpolating over the disabled period when next enabled
  30102. this._lastFrameTimeMs = null;
  30103. this._lastChangeTimeMs = null;
  30104. //wipe record
  30105. this._rollingFrameTime.reset();
  30106. };
  30107. return PerformanceMonitor;
  30108. }());
  30109. BABYLON.PerformanceMonitor = PerformanceMonitor;
  30110. /**
  30111. * RollingAverage
  30112. *
  30113. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  30114. */
  30115. var RollingAverage = (function () {
  30116. /**
  30117. * constructor
  30118. * @param length The number of samples required to saturate the sliding window
  30119. */
  30120. function RollingAverage(length) {
  30121. this._samples = new Array(length);
  30122. this.reset();
  30123. }
  30124. /**
  30125. * Adds a sample to the sample set
  30126. * @param v The sample value
  30127. */
  30128. RollingAverage.prototype.add = function (v) {
  30129. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  30130. var delta;
  30131. //we need to check if we've already wrapped round
  30132. if (this.isSaturated()) {
  30133. //remove bottom of stack from mean
  30134. var bottomValue = this._samples[this._pos];
  30135. delta = bottomValue - this.average;
  30136. this.average -= delta / (this._sampleCount - 1);
  30137. this._m2 -= delta * (bottomValue - this.average);
  30138. }
  30139. else {
  30140. this._sampleCount++;
  30141. }
  30142. //add new value to mean
  30143. delta = v - this.average;
  30144. this.average += delta / (this._sampleCount);
  30145. this._m2 += delta * (v - this.average);
  30146. //set the new variance
  30147. this.variance = this._m2 / (this._sampleCount - 1);
  30148. this._samples[this._pos] = v;
  30149. this._pos++;
  30150. this._pos %= this._samples.length; //positive wrap around
  30151. };
  30152. /**
  30153. * Returns previously added values or null if outside of history or outside the sliding window domain
  30154. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  30155. * @return Value previously recorded with add() or null if outside of range
  30156. */
  30157. RollingAverage.prototype.history = function (i) {
  30158. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  30159. return null;
  30160. }
  30161. var i0 = this._wrapPosition(this._pos - 1.0);
  30162. return this._samples[this._wrapPosition(i0 - i)];
  30163. };
  30164. /**
  30165. * Returns true if enough samples have been taken to completely fill the sliding window
  30166. * @return true if sample-set saturated
  30167. */
  30168. RollingAverage.prototype.isSaturated = function () {
  30169. return this._sampleCount >= this._samples.length;
  30170. };
  30171. /**
  30172. * Resets the rolling average (equivalent to 0 samples taken so far)
  30173. */
  30174. RollingAverage.prototype.reset = function () {
  30175. this.average = 0;
  30176. this.variance = 0;
  30177. this._sampleCount = 0;
  30178. this._pos = 0;
  30179. this._m2 = 0;
  30180. };
  30181. /**
  30182. * Wraps a value around the sample range boundaries
  30183. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30184. * @return Wrapped position in sample range
  30185. */
  30186. RollingAverage.prototype._wrapPosition = function (i) {
  30187. var max = this._samples.length;
  30188. return ((i % max) + max) % max;
  30189. };
  30190. return RollingAverage;
  30191. }());
  30192. BABYLON.RollingAverage = RollingAverage;
  30193. })(BABYLON || (BABYLON = {}));
  30194. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30195. var BABYLON;
  30196. (function (BABYLON) {
  30197. var AnimationRange = (function () {
  30198. function AnimationRange(name, from, to) {
  30199. this.name = name;
  30200. this.from = from;
  30201. this.to = to;
  30202. }
  30203. AnimationRange.prototype.clone = function () {
  30204. return new AnimationRange(this.name, this.from, this.to);
  30205. };
  30206. return AnimationRange;
  30207. }());
  30208. BABYLON.AnimationRange = AnimationRange;
  30209. /**
  30210. * Composed of a frame, and an action function
  30211. */
  30212. var AnimationEvent = (function () {
  30213. function AnimationEvent(frame, action, onlyOnce) {
  30214. this.frame = frame;
  30215. this.action = action;
  30216. this.onlyOnce = onlyOnce;
  30217. this.isDone = false;
  30218. }
  30219. return AnimationEvent;
  30220. }());
  30221. BABYLON.AnimationEvent = AnimationEvent;
  30222. var PathCursor = (function () {
  30223. function PathCursor(path) {
  30224. this.path = path;
  30225. this._onchange = new Array();
  30226. this.value = 0;
  30227. this.animations = new Array();
  30228. }
  30229. PathCursor.prototype.getPoint = function () {
  30230. var point = this.path.getPointAtLengthPosition(this.value);
  30231. return new BABYLON.Vector3(point.x, 0, point.y);
  30232. };
  30233. PathCursor.prototype.moveAhead = function (step) {
  30234. if (step === void 0) { step = 0.002; }
  30235. this.move(step);
  30236. return this;
  30237. };
  30238. PathCursor.prototype.moveBack = function (step) {
  30239. if (step === void 0) { step = 0.002; }
  30240. this.move(-step);
  30241. return this;
  30242. };
  30243. PathCursor.prototype.move = function (step) {
  30244. if (Math.abs(step) > 1) {
  30245. throw "step size should be less than 1.";
  30246. }
  30247. this.value += step;
  30248. this.ensureLimits();
  30249. this.raiseOnChange();
  30250. return this;
  30251. };
  30252. PathCursor.prototype.ensureLimits = function () {
  30253. while (this.value > 1) {
  30254. this.value -= 1;
  30255. }
  30256. while (this.value < 0) {
  30257. this.value += 1;
  30258. }
  30259. return this;
  30260. };
  30261. // used by animation engine
  30262. PathCursor.prototype.markAsDirty = function (propertyName) {
  30263. this.ensureLimits();
  30264. this.raiseOnChange();
  30265. return this;
  30266. };
  30267. PathCursor.prototype.raiseOnChange = function () {
  30268. var _this = this;
  30269. this._onchange.forEach(function (f) { return f(_this); });
  30270. return this;
  30271. };
  30272. PathCursor.prototype.onchange = function (f) {
  30273. this._onchange.push(f);
  30274. return this;
  30275. };
  30276. return PathCursor;
  30277. }());
  30278. BABYLON.PathCursor = PathCursor;
  30279. var Animation = (function () {
  30280. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  30281. this.name = name;
  30282. this.targetProperty = targetProperty;
  30283. this.framePerSecond = framePerSecond;
  30284. this.dataType = dataType;
  30285. this.loopMode = loopMode;
  30286. this.enableBlending = enableBlending;
  30287. this._offsetsCache = {};
  30288. this._highLimitsCache = {};
  30289. this._stopped = false;
  30290. this._blendingFactor = 0;
  30291. // The set of event that will be linked to this animation
  30292. this._events = new Array();
  30293. this.blendingSpeed = 0.01;
  30294. this._ranges = {};
  30295. this.targetPropertyPath = targetProperty.split(".");
  30296. this.dataType = dataType;
  30297. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  30298. }
  30299. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  30300. var dataType = undefined;
  30301. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  30302. dataType = Animation.ANIMATIONTYPE_FLOAT;
  30303. }
  30304. else if (from instanceof BABYLON.Quaternion) {
  30305. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  30306. }
  30307. else if (from instanceof BABYLON.Vector3) {
  30308. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  30309. }
  30310. else if (from instanceof BABYLON.Vector2) {
  30311. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  30312. }
  30313. else if (from instanceof BABYLON.Color3) {
  30314. dataType = Animation.ANIMATIONTYPE_COLOR3;
  30315. }
  30316. else if (from instanceof BABYLON.Size) {
  30317. dataType = Animation.ANIMATIONTYPE_SIZE;
  30318. }
  30319. if (dataType == undefined) {
  30320. return null;
  30321. }
  30322. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  30323. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  30324. animation.setKeys(keys);
  30325. if (easingFunction !== undefined) {
  30326. animation.setEasingFunction(easingFunction);
  30327. }
  30328. return animation;
  30329. };
  30330. /**
  30331. * Sets up an animation.
  30332. * @param property the property to animate
  30333. * @param animationType the animation type to apply
  30334. * @param easingFunction the easing function used in the animation
  30335. * @returns The created animation
  30336. */
  30337. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  30338. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  30339. animation.setEasingFunction(easingFunction);
  30340. return animation;
  30341. };
  30342. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30343. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30344. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30345. };
  30346. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30347. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30348. node.animations.push(animation);
  30349. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30350. };
  30351. /**
  30352. * Transition property of the Camera to the target Value.
  30353. * @param property The property to transition
  30354. * @param targetValue The target Value of the property
  30355. * @param host The object where the property to animate belongs
  30356. * @param scene Scene used to run the animation
  30357. * @param frameRate Framerate (in frame/s) to use
  30358. * @param transition The transition type we want to use
  30359. * @param duration The duration of the animation, in milliseconds
  30360. * @param onAnimationEnd Call back trigger at the end of the animation.
  30361. */
  30362. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  30363. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  30364. if (duration <= 0) {
  30365. host[property] = targetValue;
  30366. if (onAnimationEnd) {
  30367. onAnimationEnd();
  30368. }
  30369. return;
  30370. }
  30371. var endFrame = frameRate * (duration / 1000);
  30372. transition.setKeys([{
  30373. frame: 0,
  30374. value: host[property].clone ? host[property].clone() : host[property]
  30375. },
  30376. {
  30377. frame: endFrame,
  30378. value: targetValue
  30379. }]);
  30380. if (!host.animations) {
  30381. host.animations = [];
  30382. }
  30383. host.animations.push(transition);
  30384. var animation = scene.beginAnimation(host, 0, endFrame, false);
  30385. animation.onAnimationEnd = onAnimationEnd;
  30386. return animation;
  30387. };
  30388. // Methods
  30389. /**
  30390. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30391. */
  30392. Animation.prototype.toString = function (fullDetails) {
  30393. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  30394. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  30395. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  30396. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  30397. if (fullDetails) {
  30398. ret += ", Ranges: {";
  30399. var first = true;
  30400. for (var name in this._ranges) {
  30401. if (first) {
  30402. ret += ", ";
  30403. first = false;
  30404. }
  30405. ret += name;
  30406. }
  30407. ret += "}";
  30408. }
  30409. return ret;
  30410. };
  30411. /**
  30412. * Add an event to this animation.
  30413. */
  30414. Animation.prototype.addEvent = function (event) {
  30415. this._events.push(event);
  30416. };
  30417. /**
  30418. * Remove all events found at the given frame
  30419. * @param frame
  30420. */
  30421. Animation.prototype.removeEvents = function (frame) {
  30422. for (var index = 0; index < this._events.length; index++) {
  30423. if (this._events[index].frame === frame) {
  30424. this._events.splice(index, 1);
  30425. index--;
  30426. }
  30427. }
  30428. };
  30429. Animation.prototype.createRange = function (name, from, to) {
  30430. // check name not already in use; could happen for bones after serialized
  30431. if (!this._ranges[name]) {
  30432. this._ranges[name] = new AnimationRange(name, from, to);
  30433. }
  30434. };
  30435. Animation.prototype.deleteRange = function (name, deleteFrames) {
  30436. if (deleteFrames === void 0) { deleteFrames = true; }
  30437. if (this._ranges[name]) {
  30438. if (deleteFrames) {
  30439. var from = this._ranges[name].from;
  30440. var to = this._ranges[name].to;
  30441. // this loop MUST go high to low for multiple splices to work
  30442. for (var key = this._keys.length - 1; key >= 0; key--) {
  30443. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  30444. this._keys.splice(key, 1);
  30445. }
  30446. }
  30447. }
  30448. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  30449. }
  30450. };
  30451. Animation.prototype.getRange = function (name) {
  30452. return this._ranges[name];
  30453. };
  30454. Animation.prototype.reset = function () {
  30455. this._offsetsCache = {};
  30456. this._highLimitsCache = {};
  30457. this.currentFrame = 0;
  30458. this._blendingFactor = 0;
  30459. this._originalBlendValue = null;
  30460. };
  30461. Animation.prototype.isStopped = function () {
  30462. return this._stopped;
  30463. };
  30464. Animation.prototype.getKeys = function () {
  30465. return this._keys;
  30466. };
  30467. Animation.prototype.getHighestFrame = function () {
  30468. var ret = 0;
  30469. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  30470. if (ret < this._keys[key].frame) {
  30471. ret = this._keys[key].frame;
  30472. }
  30473. }
  30474. return ret;
  30475. };
  30476. Animation.prototype.getEasingFunction = function () {
  30477. return this._easingFunction;
  30478. };
  30479. Animation.prototype.setEasingFunction = function (easingFunction) {
  30480. this._easingFunction = easingFunction;
  30481. };
  30482. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  30483. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  30484. };
  30485. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30486. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30487. };
  30488. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  30489. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  30490. };
  30491. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30492. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  30493. };
  30494. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  30495. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  30496. };
  30497. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30498. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30499. };
  30500. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  30501. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  30502. };
  30503. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30504. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30505. };
  30506. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  30507. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  30508. };
  30509. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  30510. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  30511. };
  30512. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  30513. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  30514. };
  30515. Animation.prototype.clone = function () {
  30516. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  30517. clone.enableBlending = this.enableBlending;
  30518. clone.blendingSpeed = this.blendingSpeed;
  30519. if (this._keys) {
  30520. clone.setKeys(this._keys);
  30521. }
  30522. if (this._ranges) {
  30523. clone._ranges = {};
  30524. for (var name in this._ranges) {
  30525. clone._ranges[name] = this._ranges[name].clone();
  30526. }
  30527. }
  30528. return clone;
  30529. };
  30530. Animation.prototype.setKeys = function (values) {
  30531. this._keys = values.slice(0);
  30532. this._offsetsCache = {};
  30533. this._highLimitsCache = {};
  30534. };
  30535. Animation.prototype._getKeyValue = function (value) {
  30536. if (typeof value === "function") {
  30537. return value();
  30538. }
  30539. return value;
  30540. };
  30541. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  30542. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  30543. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  30544. }
  30545. this.currentFrame = currentFrame;
  30546. // Try to get a hash to find the right key
  30547. 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));
  30548. if (this._keys[startKeyIndex].frame >= currentFrame) {
  30549. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  30550. startKeyIndex--;
  30551. }
  30552. }
  30553. for (var key = startKeyIndex; key < this._keys.length; key++) {
  30554. var endKey = this._keys[key + 1];
  30555. if (endKey.frame >= currentFrame) {
  30556. var startKey = this._keys[key];
  30557. var startValue = this._getKeyValue(startKey.value);
  30558. var endValue = this._getKeyValue(endKey.value);
  30559. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  30560. var frameDelta = endKey.frame - startKey.frame;
  30561. // gradient : percent of currentFrame between the frame inf and the frame sup
  30562. var gradient = (currentFrame - startKey.frame) / frameDelta;
  30563. // check for easingFunction and correction of gradient
  30564. if (this._easingFunction != null) {
  30565. gradient = this._easingFunction.ease(gradient);
  30566. }
  30567. switch (this.dataType) {
  30568. // Float
  30569. case Animation.ANIMATIONTYPE_FLOAT:
  30570. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  30571. switch (loopMode) {
  30572. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30573. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30574. return floatValue;
  30575. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30576. return offsetValue * repeatCount + floatValue;
  30577. }
  30578. break;
  30579. // Quaternion
  30580. case Animation.ANIMATIONTYPE_QUATERNION:
  30581. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  30582. switch (loopMode) {
  30583. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30584. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30585. return quatValue;
  30586. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30587. return quatValue.add(offsetValue.scale(repeatCount));
  30588. }
  30589. return quatValue;
  30590. // Vector3
  30591. case Animation.ANIMATIONTYPE_VECTOR3:
  30592. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  30593. switch (loopMode) {
  30594. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30595. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30596. return vec3Value;
  30597. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30598. return vec3Value.add(offsetValue.scale(repeatCount));
  30599. }
  30600. // Vector2
  30601. case Animation.ANIMATIONTYPE_VECTOR2:
  30602. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  30603. switch (loopMode) {
  30604. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30605. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30606. return vec2Value;
  30607. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30608. return vec2Value.add(offsetValue.scale(repeatCount));
  30609. }
  30610. // Size
  30611. case Animation.ANIMATIONTYPE_SIZE:
  30612. switch (loopMode) {
  30613. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30614. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30615. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30616. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30617. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30618. }
  30619. // Color3
  30620. case Animation.ANIMATIONTYPE_COLOR3:
  30621. switch (loopMode) {
  30622. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30623. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30624. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30625. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30626. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30627. }
  30628. // Matrix
  30629. case Animation.ANIMATIONTYPE_MATRIX:
  30630. switch (loopMode) {
  30631. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30632. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30633. if (Animation.AllowMatricesInterpolation) {
  30634. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30635. }
  30636. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30637. return startValue;
  30638. }
  30639. default:
  30640. break;
  30641. }
  30642. break;
  30643. }
  30644. }
  30645. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30646. };
  30647. Animation.prototype.setValue = function (currentValue, blend) {
  30648. if (blend === void 0) { blend = false; }
  30649. // Set value
  30650. var path;
  30651. var destination;
  30652. if (this.targetPropertyPath.length > 1) {
  30653. var property = this._target[this.targetPropertyPath[0]];
  30654. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30655. property = property[this.targetPropertyPath[index]];
  30656. }
  30657. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30658. destination = property;
  30659. }
  30660. else {
  30661. path = this.targetPropertyPath[0];
  30662. destination = this._target;
  30663. }
  30664. // Blending
  30665. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30666. if (!this._originalBlendValue) {
  30667. if (destination[path].clone) {
  30668. this._originalBlendValue = destination[path].clone();
  30669. }
  30670. else {
  30671. this._originalBlendValue = destination[path];
  30672. }
  30673. }
  30674. if (this._originalBlendValue.prototype) {
  30675. if (this._originalBlendValue.prototype.Lerp) {
  30676. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30677. }
  30678. else {
  30679. destination[path] = currentValue;
  30680. }
  30681. }
  30682. else if (this._originalBlendValue.m) {
  30683. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30684. }
  30685. else {
  30686. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30687. }
  30688. this._blendingFactor += this.blendingSpeed;
  30689. }
  30690. else {
  30691. destination[path] = currentValue;
  30692. }
  30693. if (this._target.markAsDirty) {
  30694. this._target.markAsDirty(this.targetProperty);
  30695. }
  30696. };
  30697. Animation.prototype.goToFrame = function (frame) {
  30698. if (frame < this._keys[0].frame) {
  30699. frame = this._keys[0].frame;
  30700. }
  30701. else if (frame > this._keys[this._keys.length - 1].frame) {
  30702. frame = this._keys[this._keys.length - 1].frame;
  30703. }
  30704. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30705. this.setValue(currentValue);
  30706. };
  30707. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30708. if (blend === void 0) { blend = false; }
  30709. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30710. this._stopped = true;
  30711. return false;
  30712. }
  30713. var returnValue = true;
  30714. // Adding a start key at frame 0 if missing
  30715. if (this._keys[0].frame !== 0) {
  30716. var newKey = { frame: 0, value: this._keys[0].value };
  30717. this._keys.splice(0, 0, newKey);
  30718. }
  30719. // Check limits
  30720. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30721. from = this._keys[0].frame;
  30722. }
  30723. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30724. to = this._keys[this._keys.length - 1].frame;
  30725. }
  30726. //to and from cannot be the same key
  30727. if (from === to) {
  30728. from++;
  30729. }
  30730. // Compute ratio
  30731. var range = to - from;
  30732. var offsetValue;
  30733. // ratio represents the frame delta between from and to
  30734. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30735. var highLimitValue = 0;
  30736. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  30737. returnValue = false;
  30738. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30739. }
  30740. else {
  30741. // Get max value if required
  30742. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30743. var keyOffset = to.toString() + from.toString();
  30744. if (!this._offsetsCache[keyOffset]) {
  30745. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30746. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30747. switch (this.dataType) {
  30748. // Float
  30749. case Animation.ANIMATIONTYPE_FLOAT:
  30750. this._offsetsCache[keyOffset] = toValue - fromValue;
  30751. break;
  30752. // Quaternion
  30753. case Animation.ANIMATIONTYPE_QUATERNION:
  30754. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30755. break;
  30756. // Vector3
  30757. case Animation.ANIMATIONTYPE_VECTOR3:
  30758. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30759. // Vector2
  30760. case Animation.ANIMATIONTYPE_VECTOR2:
  30761. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30762. // Size
  30763. case Animation.ANIMATIONTYPE_SIZE:
  30764. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30765. // Color3
  30766. case Animation.ANIMATIONTYPE_COLOR3:
  30767. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30768. default:
  30769. break;
  30770. }
  30771. this._highLimitsCache[keyOffset] = toValue;
  30772. }
  30773. highLimitValue = this._highLimitsCache[keyOffset];
  30774. offsetValue = this._offsetsCache[keyOffset];
  30775. }
  30776. }
  30777. if (offsetValue === undefined) {
  30778. switch (this.dataType) {
  30779. // Float
  30780. case Animation.ANIMATIONTYPE_FLOAT:
  30781. offsetValue = 0;
  30782. break;
  30783. // Quaternion
  30784. case Animation.ANIMATIONTYPE_QUATERNION:
  30785. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30786. break;
  30787. // Vector3
  30788. case Animation.ANIMATIONTYPE_VECTOR3:
  30789. offsetValue = BABYLON.Vector3.Zero();
  30790. break;
  30791. // Vector2
  30792. case Animation.ANIMATIONTYPE_VECTOR2:
  30793. offsetValue = BABYLON.Vector2.Zero();
  30794. break;
  30795. // Size
  30796. case Animation.ANIMATIONTYPE_SIZE:
  30797. offsetValue = BABYLON.Size.Zero();
  30798. break;
  30799. // Color3
  30800. case Animation.ANIMATIONTYPE_COLOR3:
  30801. offsetValue = BABYLON.Color3.Black();
  30802. }
  30803. }
  30804. // Compute value
  30805. var repeatCount = (ratio / range) >> 0;
  30806. var currentFrame = returnValue ? from + ratio % range : to;
  30807. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30808. // Set value
  30809. this.setValue(currentValue);
  30810. // Check events
  30811. for (var index = 0; index < this._events.length; index++) {
  30812. // Make sure current frame has passed event frame and that event frame is within the current range
  30813. // Also, handle both forward and reverse animations
  30814. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  30815. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  30816. var event = this._events[index];
  30817. if (!event.isDone) {
  30818. // If event should be done only once, remove it.
  30819. if (event.onlyOnce) {
  30820. this._events.splice(index, 1);
  30821. index--;
  30822. }
  30823. event.isDone = true;
  30824. event.action();
  30825. } // Don't do anything if the event has already be done.
  30826. }
  30827. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30828. // reset event, the animation is looping
  30829. this._events[index].isDone = false;
  30830. }
  30831. }
  30832. if (!returnValue) {
  30833. this._stopped = true;
  30834. }
  30835. return returnValue;
  30836. };
  30837. Animation.prototype.serialize = function () {
  30838. var serializationObject = {};
  30839. serializationObject.name = this.name;
  30840. serializationObject.property = this.targetProperty;
  30841. serializationObject.framePerSecond = this.framePerSecond;
  30842. serializationObject.dataType = this.dataType;
  30843. serializationObject.loopBehavior = this.loopMode;
  30844. serializationObject.enableBlending = this.enableBlending;
  30845. serializationObject.blendingSpeed = this.blendingSpeed;
  30846. var dataType = this.dataType;
  30847. serializationObject.keys = [];
  30848. var keys = this.getKeys();
  30849. for (var index = 0; index < keys.length; index++) {
  30850. var animationKey = keys[index];
  30851. var key = {};
  30852. key.frame = animationKey.frame;
  30853. switch (dataType) {
  30854. case Animation.ANIMATIONTYPE_FLOAT:
  30855. key.values = [animationKey.value];
  30856. break;
  30857. case Animation.ANIMATIONTYPE_QUATERNION:
  30858. case Animation.ANIMATIONTYPE_MATRIX:
  30859. case Animation.ANIMATIONTYPE_VECTOR3:
  30860. case Animation.ANIMATIONTYPE_COLOR3:
  30861. key.values = animationKey.value.asArray();
  30862. break;
  30863. }
  30864. serializationObject.keys.push(key);
  30865. }
  30866. serializationObject.ranges = [];
  30867. for (var name in this._ranges) {
  30868. var range = {};
  30869. range.name = name;
  30870. range.from = this._ranges[name].from;
  30871. range.to = this._ranges[name].to;
  30872. serializationObject.ranges.push(range);
  30873. }
  30874. return serializationObject;
  30875. };
  30876. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30877. get: function () {
  30878. return Animation._ANIMATIONTYPE_FLOAT;
  30879. },
  30880. enumerable: true,
  30881. configurable: true
  30882. });
  30883. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30884. get: function () {
  30885. return Animation._ANIMATIONTYPE_VECTOR3;
  30886. },
  30887. enumerable: true,
  30888. configurable: true
  30889. });
  30890. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30891. get: function () {
  30892. return Animation._ANIMATIONTYPE_VECTOR2;
  30893. },
  30894. enumerable: true,
  30895. configurable: true
  30896. });
  30897. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30898. get: function () {
  30899. return Animation._ANIMATIONTYPE_SIZE;
  30900. },
  30901. enumerable: true,
  30902. configurable: true
  30903. });
  30904. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30905. get: function () {
  30906. return Animation._ANIMATIONTYPE_QUATERNION;
  30907. },
  30908. enumerable: true,
  30909. configurable: true
  30910. });
  30911. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30912. get: function () {
  30913. return Animation._ANIMATIONTYPE_MATRIX;
  30914. },
  30915. enumerable: true,
  30916. configurable: true
  30917. });
  30918. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30919. get: function () {
  30920. return Animation._ANIMATIONTYPE_COLOR3;
  30921. },
  30922. enumerable: true,
  30923. configurable: true
  30924. });
  30925. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30926. get: function () {
  30927. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30928. },
  30929. enumerable: true,
  30930. configurable: true
  30931. });
  30932. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30933. get: function () {
  30934. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30935. },
  30936. enumerable: true,
  30937. configurable: true
  30938. });
  30939. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30940. get: function () {
  30941. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30942. },
  30943. enumerable: true,
  30944. configurable: true
  30945. });
  30946. Animation.Parse = function (parsedAnimation) {
  30947. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30948. var dataType = parsedAnimation.dataType;
  30949. var keys = [];
  30950. var data;
  30951. var index;
  30952. if (parsedAnimation.enableBlending) {
  30953. animation.enableBlending = parsedAnimation.enableBlending;
  30954. }
  30955. if (parsedAnimation.blendingSpeed) {
  30956. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30957. }
  30958. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30959. var key = parsedAnimation.keys[index];
  30960. switch (dataType) {
  30961. case Animation.ANIMATIONTYPE_FLOAT:
  30962. data = key.values[0];
  30963. break;
  30964. case Animation.ANIMATIONTYPE_QUATERNION:
  30965. data = BABYLON.Quaternion.FromArray(key.values);
  30966. break;
  30967. case Animation.ANIMATIONTYPE_MATRIX:
  30968. data = BABYLON.Matrix.FromArray(key.values);
  30969. break;
  30970. case Animation.ANIMATIONTYPE_COLOR3:
  30971. data = BABYLON.Color3.FromArray(key.values);
  30972. break;
  30973. case Animation.ANIMATIONTYPE_VECTOR3:
  30974. default:
  30975. data = BABYLON.Vector3.FromArray(key.values);
  30976. break;
  30977. }
  30978. keys.push({
  30979. frame: key.frame,
  30980. value: data
  30981. });
  30982. }
  30983. animation.setKeys(keys);
  30984. if (parsedAnimation.ranges) {
  30985. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30986. data = parsedAnimation.ranges[index];
  30987. animation.createRange(data.name, data.from, data.to);
  30988. }
  30989. }
  30990. return animation;
  30991. };
  30992. Animation.AppendSerializedAnimations = function (source, destination) {
  30993. if (source.animations) {
  30994. destination.animations = [];
  30995. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30996. var animation = source.animations[animationIndex];
  30997. destination.animations.push(animation.serialize());
  30998. }
  30999. }
  31000. };
  31001. Animation.AllowMatricesInterpolation = false;
  31002. // Statics
  31003. Animation._ANIMATIONTYPE_FLOAT = 0;
  31004. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  31005. Animation._ANIMATIONTYPE_QUATERNION = 2;
  31006. Animation._ANIMATIONTYPE_MATRIX = 3;
  31007. Animation._ANIMATIONTYPE_COLOR3 = 4;
  31008. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  31009. Animation._ANIMATIONTYPE_SIZE = 6;
  31010. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  31011. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  31012. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  31013. return Animation;
  31014. }());
  31015. BABYLON.Animation = Animation;
  31016. })(BABYLON || (BABYLON = {}));
  31017. //# sourceMappingURL=babylon.animation.js.map
  31018. var BABYLON;
  31019. (function (BABYLON) {
  31020. var Animatable = (function () {
  31021. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  31022. if (fromFrame === void 0) { fromFrame = 0; }
  31023. if (toFrame === void 0) { toFrame = 100; }
  31024. if (loopAnimation === void 0) { loopAnimation = false; }
  31025. if (speedRatio === void 0) { speedRatio = 1.0; }
  31026. this.target = target;
  31027. this.fromFrame = fromFrame;
  31028. this.toFrame = toFrame;
  31029. this.loopAnimation = loopAnimation;
  31030. this.speedRatio = speedRatio;
  31031. this.onAnimationEnd = onAnimationEnd;
  31032. this._localDelayOffset = null;
  31033. this._pausedDelay = null;
  31034. this._animations = new Array();
  31035. this._paused = false;
  31036. this.animationStarted = false;
  31037. if (animations) {
  31038. this.appendAnimations(target, animations);
  31039. }
  31040. this._scene = scene;
  31041. scene._activeAnimatables.push(this);
  31042. }
  31043. // Methods
  31044. Animatable.prototype.getAnimations = function () {
  31045. return this._animations;
  31046. };
  31047. Animatable.prototype.appendAnimations = function (target, animations) {
  31048. for (var index = 0; index < animations.length; index++) {
  31049. var animation = animations[index];
  31050. animation._target = target;
  31051. this._animations.push(animation);
  31052. }
  31053. };
  31054. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  31055. var animations = this._animations;
  31056. for (var index = 0; index < animations.length; index++) {
  31057. if (animations[index].targetProperty === property) {
  31058. return animations[index];
  31059. }
  31060. }
  31061. return null;
  31062. };
  31063. Animatable.prototype.reset = function () {
  31064. var animations = this._animations;
  31065. for (var index = 0; index < animations.length; index++) {
  31066. animations[index].reset();
  31067. }
  31068. this._localDelayOffset = null;
  31069. this._pausedDelay = null;
  31070. };
  31071. Animatable.prototype.enableBlending = function (blendingSpeed) {
  31072. var animations = this._animations;
  31073. for (var index = 0; index < animations.length; index++) {
  31074. animations[index].enableBlending = true;
  31075. animations[index].blendingSpeed = blendingSpeed;
  31076. }
  31077. };
  31078. Animatable.prototype.disableBlending = function () {
  31079. var animations = this._animations;
  31080. for (var index = 0; index < animations.length; index++) {
  31081. animations[index].enableBlending = false;
  31082. }
  31083. };
  31084. Animatable.prototype.goToFrame = function (frame) {
  31085. var animations = this._animations;
  31086. if (animations[0]) {
  31087. var fps = animations[0].framePerSecond;
  31088. var currentFrame = animations[0].currentFrame;
  31089. var adjustTime = frame - currentFrame;
  31090. var delay = adjustTime * 1000 / fps;
  31091. this._localDelayOffset -= delay;
  31092. }
  31093. for (var index = 0; index < animations.length; index++) {
  31094. animations[index].goToFrame(frame);
  31095. }
  31096. };
  31097. Animatable.prototype.pause = function () {
  31098. if (this._paused) {
  31099. return;
  31100. }
  31101. this._paused = true;
  31102. };
  31103. Animatable.prototype.restart = function () {
  31104. this._paused = false;
  31105. };
  31106. Animatable.prototype.stop = function (animationName) {
  31107. if (animationName) {
  31108. var idx = this._scene._activeAnimatables.indexOf(this);
  31109. if (idx > -1) {
  31110. var animations = this._animations;
  31111. for (var index = animations.length - 1; index >= 0; index--) {
  31112. if (typeof animationName === "string" && animations[index].name != animationName) {
  31113. continue;
  31114. }
  31115. animations[index].reset();
  31116. animations.splice(index, 1);
  31117. }
  31118. if (animations.length == 0) {
  31119. this._scene._activeAnimatables.splice(idx, 1);
  31120. if (this.onAnimationEnd) {
  31121. this.onAnimationEnd();
  31122. }
  31123. }
  31124. }
  31125. }
  31126. else {
  31127. var index = this._scene._activeAnimatables.indexOf(this);
  31128. if (index > -1) {
  31129. this._scene._activeAnimatables.splice(index, 1);
  31130. var animations = this._animations;
  31131. for (var index = 0; index < animations.length; index++) {
  31132. animations[index].reset();
  31133. }
  31134. if (this.onAnimationEnd) {
  31135. this.onAnimationEnd();
  31136. }
  31137. }
  31138. }
  31139. };
  31140. Animatable.prototype._animate = function (delay) {
  31141. if (this._paused) {
  31142. this.animationStarted = false;
  31143. if (this._pausedDelay === null) {
  31144. this._pausedDelay = delay;
  31145. }
  31146. return true;
  31147. }
  31148. if (this._localDelayOffset === null) {
  31149. this._localDelayOffset = delay;
  31150. }
  31151. else if (this._pausedDelay !== null) {
  31152. this._localDelayOffset += delay - this._pausedDelay;
  31153. this._pausedDelay = null;
  31154. }
  31155. // Animating
  31156. var running = false;
  31157. var animations = this._animations;
  31158. var index;
  31159. for (index = 0; index < animations.length; index++) {
  31160. var animation = animations[index];
  31161. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  31162. running = running || isRunning;
  31163. }
  31164. this.animationStarted = running;
  31165. if (!running) {
  31166. // Remove from active animatables
  31167. index = this._scene._activeAnimatables.indexOf(this);
  31168. this._scene._activeAnimatables.splice(index, 1);
  31169. }
  31170. if (!running && this.onAnimationEnd) {
  31171. this.onAnimationEnd();
  31172. this.onAnimationEnd = null;
  31173. }
  31174. return running;
  31175. };
  31176. return Animatable;
  31177. }());
  31178. BABYLON.Animatable = Animatable;
  31179. })(BABYLON || (BABYLON = {}));
  31180. //# sourceMappingURL=babylon.animatable.js.map
  31181. var BABYLON;
  31182. (function (BABYLON) {
  31183. var EasingFunction = (function () {
  31184. function EasingFunction() {
  31185. // Properties
  31186. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  31187. }
  31188. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  31189. get: function () {
  31190. return EasingFunction._EASINGMODE_EASEIN;
  31191. },
  31192. enumerable: true,
  31193. configurable: true
  31194. });
  31195. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  31196. get: function () {
  31197. return EasingFunction._EASINGMODE_EASEOUT;
  31198. },
  31199. enumerable: true,
  31200. configurable: true
  31201. });
  31202. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  31203. get: function () {
  31204. return EasingFunction._EASINGMODE_EASEINOUT;
  31205. },
  31206. enumerable: true,
  31207. configurable: true
  31208. });
  31209. EasingFunction.prototype.setEasingMode = function (easingMode) {
  31210. var n = Math.min(Math.max(easingMode, 0), 2);
  31211. this._easingMode = n;
  31212. };
  31213. EasingFunction.prototype.getEasingMode = function () {
  31214. return this._easingMode;
  31215. };
  31216. EasingFunction.prototype.easeInCore = function (gradient) {
  31217. throw new Error('You must implement this method');
  31218. };
  31219. EasingFunction.prototype.ease = function (gradient) {
  31220. switch (this._easingMode) {
  31221. case EasingFunction.EASINGMODE_EASEIN:
  31222. return this.easeInCore(gradient);
  31223. case EasingFunction.EASINGMODE_EASEOUT:
  31224. return (1 - this.easeInCore(1 - gradient));
  31225. }
  31226. if (gradient >= 0.5) {
  31227. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  31228. }
  31229. return (this.easeInCore(gradient * 2) * 0.5);
  31230. };
  31231. //Statics
  31232. EasingFunction._EASINGMODE_EASEIN = 0;
  31233. EasingFunction._EASINGMODE_EASEOUT = 1;
  31234. EasingFunction._EASINGMODE_EASEINOUT = 2;
  31235. return EasingFunction;
  31236. }());
  31237. BABYLON.EasingFunction = EasingFunction;
  31238. var CircleEase = (function (_super) {
  31239. __extends(CircleEase, _super);
  31240. function CircleEase() {
  31241. return _super !== null && _super.apply(this, arguments) || this;
  31242. }
  31243. CircleEase.prototype.easeInCore = function (gradient) {
  31244. gradient = Math.max(0, Math.min(1, gradient));
  31245. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  31246. };
  31247. return CircleEase;
  31248. }(EasingFunction));
  31249. BABYLON.CircleEase = CircleEase;
  31250. var BackEase = (function (_super) {
  31251. __extends(BackEase, _super);
  31252. function BackEase(amplitude) {
  31253. if (amplitude === void 0) { amplitude = 1; }
  31254. var _this = _super.call(this) || this;
  31255. _this.amplitude = amplitude;
  31256. return _this;
  31257. }
  31258. BackEase.prototype.easeInCore = function (gradient) {
  31259. var num = Math.max(0, this.amplitude);
  31260. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  31261. };
  31262. return BackEase;
  31263. }(EasingFunction));
  31264. BABYLON.BackEase = BackEase;
  31265. var BounceEase = (function (_super) {
  31266. __extends(BounceEase, _super);
  31267. function BounceEase(bounces, bounciness) {
  31268. if (bounces === void 0) { bounces = 3; }
  31269. if (bounciness === void 0) { bounciness = 2; }
  31270. var _this = _super.call(this) || this;
  31271. _this.bounces = bounces;
  31272. _this.bounciness = bounciness;
  31273. return _this;
  31274. }
  31275. BounceEase.prototype.easeInCore = function (gradient) {
  31276. var y = Math.max(0.0, this.bounces);
  31277. var bounciness = this.bounciness;
  31278. if (bounciness <= 1.0) {
  31279. bounciness = 1.001;
  31280. }
  31281. var num9 = Math.pow(bounciness, y);
  31282. var num5 = 1.0 - bounciness;
  31283. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  31284. var num15 = gradient * num4;
  31285. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  31286. var num3 = Math.floor(num65);
  31287. var num13 = num3 + 1.0;
  31288. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  31289. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  31290. var num7 = (num8 + num12) * 0.5;
  31291. var num6 = gradient - num7;
  31292. var num2 = num7 - num8;
  31293. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  31294. };
  31295. return BounceEase;
  31296. }(EasingFunction));
  31297. BABYLON.BounceEase = BounceEase;
  31298. var CubicEase = (function (_super) {
  31299. __extends(CubicEase, _super);
  31300. function CubicEase() {
  31301. return _super !== null && _super.apply(this, arguments) || this;
  31302. }
  31303. CubicEase.prototype.easeInCore = function (gradient) {
  31304. return (gradient * gradient * gradient);
  31305. };
  31306. return CubicEase;
  31307. }(EasingFunction));
  31308. BABYLON.CubicEase = CubicEase;
  31309. var ElasticEase = (function (_super) {
  31310. __extends(ElasticEase, _super);
  31311. function ElasticEase(oscillations, springiness) {
  31312. if (oscillations === void 0) { oscillations = 3; }
  31313. if (springiness === void 0) { springiness = 3; }
  31314. var _this = _super.call(this) || this;
  31315. _this.oscillations = oscillations;
  31316. _this.springiness = springiness;
  31317. return _this;
  31318. }
  31319. ElasticEase.prototype.easeInCore = function (gradient) {
  31320. var num2;
  31321. var num3 = Math.max(0.0, this.oscillations);
  31322. var num = Math.max(0.0, this.springiness);
  31323. if (num == 0) {
  31324. num2 = gradient;
  31325. }
  31326. else {
  31327. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  31328. }
  31329. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  31330. };
  31331. return ElasticEase;
  31332. }(EasingFunction));
  31333. BABYLON.ElasticEase = ElasticEase;
  31334. var ExponentialEase = (function (_super) {
  31335. __extends(ExponentialEase, _super);
  31336. function ExponentialEase(exponent) {
  31337. if (exponent === void 0) { exponent = 2; }
  31338. var _this = _super.call(this) || this;
  31339. _this.exponent = exponent;
  31340. return _this;
  31341. }
  31342. ExponentialEase.prototype.easeInCore = function (gradient) {
  31343. if (this.exponent <= 0) {
  31344. return gradient;
  31345. }
  31346. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  31347. };
  31348. return ExponentialEase;
  31349. }(EasingFunction));
  31350. BABYLON.ExponentialEase = ExponentialEase;
  31351. var PowerEase = (function (_super) {
  31352. __extends(PowerEase, _super);
  31353. function PowerEase(power) {
  31354. if (power === void 0) { power = 2; }
  31355. var _this = _super.call(this) || this;
  31356. _this.power = power;
  31357. return _this;
  31358. }
  31359. PowerEase.prototype.easeInCore = function (gradient) {
  31360. var y = Math.max(0.0, this.power);
  31361. return Math.pow(gradient, y);
  31362. };
  31363. return PowerEase;
  31364. }(EasingFunction));
  31365. BABYLON.PowerEase = PowerEase;
  31366. var QuadraticEase = (function (_super) {
  31367. __extends(QuadraticEase, _super);
  31368. function QuadraticEase() {
  31369. return _super !== null && _super.apply(this, arguments) || this;
  31370. }
  31371. QuadraticEase.prototype.easeInCore = function (gradient) {
  31372. return (gradient * gradient);
  31373. };
  31374. return QuadraticEase;
  31375. }(EasingFunction));
  31376. BABYLON.QuadraticEase = QuadraticEase;
  31377. var QuarticEase = (function (_super) {
  31378. __extends(QuarticEase, _super);
  31379. function QuarticEase() {
  31380. return _super !== null && _super.apply(this, arguments) || this;
  31381. }
  31382. QuarticEase.prototype.easeInCore = function (gradient) {
  31383. return (gradient * gradient * gradient * gradient);
  31384. };
  31385. return QuarticEase;
  31386. }(EasingFunction));
  31387. BABYLON.QuarticEase = QuarticEase;
  31388. var QuinticEase = (function (_super) {
  31389. __extends(QuinticEase, _super);
  31390. function QuinticEase() {
  31391. return _super !== null && _super.apply(this, arguments) || this;
  31392. }
  31393. QuinticEase.prototype.easeInCore = function (gradient) {
  31394. return (gradient * gradient * gradient * gradient * gradient);
  31395. };
  31396. return QuinticEase;
  31397. }(EasingFunction));
  31398. BABYLON.QuinticEase = QuinticEase;
  31399. var SineEase = (function (_super) {
  31400. __extends(SineEase, _super);
  31401. function SineEase() {
  31402. return _super !== null && _super.apply(this, arguments) || this;
  31403. }
  31404. SineEase.prototype.easeInCore = function (gradient) {
  31405. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  31406. };
  31407. return SineEase;
  31408. }(EasingFunction));
  31409. BABYLON.SineEase = SineEase;
  31410. var BezierCurveEase = (function (_super) {
  31411. __extends(BezierCurveEase, _super);
  31412. function BezierCurveEase(x1, y1, x2, y2) {
  31413. if (x1 === void 0) { x1 = 0; }
  31414. if (y1 === void 0) { y1 = 0; }
  31415. if (x2 === void 0) { x2 = 1; }
  31416. if (y2 === void 0) { y2 = 1; }
  31417. var _this = _super.call(this) || this;
  31418. _this.x1 = x1;
  31419. _this.y1 = y1;
  31420. _this.x2 = x2;
  31421. _this.y2 = y2;
  31422. return _this;
  31423. }
  31424. BezierCurveEase.prototype.easeInCore = function (gradient) {
  31425. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  31426. };
  31427. return BezierCurveEase;
  31428. }(EasingFunction));
  31429. BABYLON.BezierCurveEase = BezierCurveEase;
  31430. })(BABYLON || (BABYLON = {}));
  31431. //# sourceMappingURL=babylon.easing.js.map
  31432. var BABYLON;
  31433. (function (BABYLON) {
  31434. BABYLON.CameraInputTypes = {};
  31435. var CameraInputsManager = (function () {
  31436. function CameraInputsManager(camera) {
  31437. this.attached = {};
  31438. this.camera = camera;
  31439. this.checkInputs = function () { };
  31440. }
  31441. CameraInputsManager.prototype.add = function (input) {
  31442. var type = input.getSimpleName();
  31443. if (this.attached[type]) {
  31444. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  31445. return;
  31446. }
  31447. this.attached[type] = input;
  31448. input.camera = this.camera;
  31449. //for checkInputs, we are dynamically creating a function
  31450. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  31451. if (input.checkInputs) {
  31452. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31453. }
  31454. if (this.attachedElement) {
  31455. input.attachControl(this.attachedElement);
  31456. }
  31457. };
  31458. CameraInputsManager.prototype.remove = function (inputToRemove) {
  31459. for (var cam in this.attached) {
  31460. var input = this.attached[cam];
  31461. if (input === inputToRemove) {
  31462. input.detachControl(this.attachedElement);
  31463. input.camera = null;
  31464. delete this.attached[cam];
  31465. this.rebuildInputCheck();
  31466. }
  31467. }
  31468. };
  31469. CameraInputsManager.prototype.removeByType = function (inputType) {
  31470. for (var cam in this.attached) {
  31471. var input = this.attached[cam];
  31472. if (input.getClassName() === inputType) {
  31473. input.detachControl(this.attachedElement);
  31474. input.camera = null;
  31475. delete this.attached[cam];
  31476. this.rebuildInputCheck();
  31477. }
  31478. }
  31479. };
  31480. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  31481. var current = this.checkInputs;
  31482. return function () {
  31483. current();
  31484. fn();
  31485. };
  31486. };
  31487. CameraInputsManager.prototype.attachInput = function (input) {
  31488. input.attachControl(this.attachedElement, this.noPreventDefault);
  31489. };
  31490. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31491. if (this.attachedElement) {
  31492. return;
  31493. }
  31494. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31495. this.attachedElement = element;
  31496. this.noPreventDefault = noPreventDefault;
  31497. for (var cam in this.attached) {
  31498. var input = this.attached[cam];
  31499. this.attached[cam].attachControl(element, noPreventDefault);
  31500. }
  31501. };
  31502. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  31503. if (disconnect === void 0) { disconnect = false; }
  31504. if (this.attachedElement !== element) {
  31505. return;
  31506. }
  31507. for (var cam in this.attached) {
  31508. var input = this.attached[cam];
  31509. this.attached[cam].detachControl(element);
  31510. if (disconnect) {
  31511. this.attached[cam].camera = null;
  31512. }
  31513. }
  31514. this.attachedElement = null;
  31515. };
  31516. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31517. this.checkInputs = function () { };
  31518. for (var cam in this.attached) {
  31519. var input = this.attached[cam];
  31520. if (input.checkInputs) {
  31521. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31522. }
  31523. }
  31524. };
  31525. CameraInputsManager.prototype.clear = function () {
  31526. if (this.attachedElement) {
  31527. this.detachElement(this.attachedElement, true);
  31528. }
  31529. this.attached = {};
  31530. this.attachedElement = null;
  31531. this.checkInputs = function () { };
  31532. };
  31533. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31534. var inputs = {};
  31535. for (var cam in this.attached) {
  31536. var input = this.attached[cam];
  31537. var res = BABYLON.SerializationHelper.Serialize(input);
  31538. inputs[input.getClassName()] = res;
  31539. }
  31540. serializedCamera.inputsmgr = inputs;
  31541. };
  31542. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31543. var parsedInputs = parsedCamera.inputsmgr;
  31544. if (parsedInputs) {
  31545. this.clear();
  31546. for (var n in parsedInputs) {
  31547. var construct = BABYLON.CameraInputTypes[n];
  31548. if (construct) {
  31549. var parsedinput = parsedInputs[n];
  31550. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31551. this.add(input);
  31552. }
  31553. }
  31554. }
  31555. else {
  31556. //2016-03-08 this part is for managing backward compatibility
  31557. for (var n in this.attached) {
  31558. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  31559. if (construct) {
  31560. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31561. this.remove(this.attached[n]);
  31562. this.add(input);
  31563. }
  31564. }
  31565. }
  31566. };
  31567. return CameraInputsManager;
  31568. }());
  31569. BABYLON.CameraInputsManager = CameraInputsManager;
  31570. })(BABYLON || (BABYLON = {}));
  31571. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31572. /// <reference path="babylon.camera.ts" />
  31573. var BABYLON;
  31574. (function (BABYLON) {
  31575. var TargetCamera = (function (_super) {
  31576. __extends(TargetCamera, _super);
  31577. function TargetCamera(name, position, scene) {
  31578. var _this = _super.call(this, name, position, scene) || this;
  31579. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  31580. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  31581. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  31582. _this.speed = 2.0;
  31583. _this.noRotationConstraint = false;
  31584. _this.lockedTarget = null;
  31585. _this._currentTarget = BABYLON.Vector3.Zero();
  31586. _this._viewMatrix = BABYLON.Matrix.Zero();
  31587. _this._camMatrix = BABYLON.Matrix.Zero();
  31588. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  31589. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  31590. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  31591. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  31592. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  31593. _this._lookAtTemp = BABYLON.Matrix.Zero();
  31594. _this._tempMatrix = BABYLON.Matrix.Zero();
  31595. return _this;
  31596. }
  31597. TargetCamera.prototype.getFrontPosition = function (distance) {
  31598. var direction = this.getTarget().subtract(this.position);
  31599. direction.normalize();
  31600. direction.scaleInPlace(distance);
  31601. return this.globalPosition.add(direction);
  31602. };
  31603. TargetCamera.prototype._getLockedTargetPosition = function () {
  31604. if (!this.lockedTarget) {
  31605. return null;
  31606. }
  31607. if (this.lockedTarget.absolutePosition) {
  31608. this.lockedTarget.computeWorldMatrix();
  31609. }
  31610. return this.lockedTarget.absolutePosition || this.lockedTarget;
  31611. };
  31612. TargetCamera.prototype.storeState = function () {
  31613. this._storedPosition = this.position.clone();
  31614. this._storedRotation = this.rotation.clone();
  31615. if (this.rotationQuaternion) {
  31616. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  31617. }
  31618. return _super.prototype.storeState.call(this);
  31619. };
  31620. /**
  31621. * Restored camera state. You must call storeState() first
  31622. */
  31623. TargetCamera.prototype.restoreState = function () {
  31624. if (!_super.prototype.restoreState.call(this)) {
  31625. return false;
  31626. }
  31627. this.position = this._storedPosition.clone();
  31628. this.rotation = this._storedRotation.clone();
  31629. if (this.rotationQuaternion) {
  31630. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  31631. }
  31632. this.cameraDirection.copyFromFloats(0, 0, 0);
  31633. this.cameraRotation.copyFromFloats(0, 0);
  31634. return true;
  31635. };
  31636. // Cache
  31637. TargetCamera.prototype._initCache = function () {
  31638. _super.prototype._initCache.call(this);
  31639. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31640. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31641. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31642. };
  31643. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  31644. if (!ignoreParentClass) {
  31645. _super.prototype._updateCache.call(this);
  31646. }
  31647. var lockedTargetPosition = this._getLockedTargetPosition();
  31648. if (!lockedTargetPosition) {
  31649. this._cache.lockedTarget = null;
  31650. }
  31651. else {
  31652. if (!this._cache.lockedTarget) {
  31653. this._cache.lockedTarget = lockedTargetPosition.clone();
  31654. }
  31655. else {
  31656. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  31657. }
  31658. }
  31659. this._cache.rotation.copyFrom(this.rotation);
  31660. if (this.rotationQuaternion)
  31661. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31662. };
  31663. // Synchronized
  31664. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  31665. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  31666. return false;
  31667. }
  31668. var lockedTargetPosition = this._getLockedTargetPosition();
  31669. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  31670. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  31671. };
  31672. // Methods
  31673. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  31674. var engine = this.getEngine();
  31675. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  31676. };
  31677. // Target
  31678. TargetCamera.prototype.setTarget = function (target) {
  31679. this.upVector.normalize();
  31680. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  31681. this._camMatrix.invert();
  31682. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  31683. var vDir = target.subtract(this.position);
  31684. if (vDir.x >= 0.0) {
  31685. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  31686. }
  31687. else {
  31688. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  31689. }
  31690. this.rotation.z = 0;
  31691. if (isNaN(this.rotation.x)) {
  31692. this.rotation.x = 0;
  31693. }
  31694. if (isNaN(this.rotation.y)) {
  31695. this.rotation.y = 0;
  31696. }
  31697. if (isNaN(this.rotation.z)) {
  31698. this.rotation.z = 0;
  31699. }
  31700. if (this.rotationQuaternion) {
  31701. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31702. }
  31703. };
  31704. /**
  31705. * Return the current target position of the camera. This value is expressed in local space.
  31706. */
  31707. TargetCamera.prototype.getTarget = function () {
  31708. return this._currentTarget;
  31709. };
  31710. TargetCamera.prototype._decideIfNeedsToMove = function () {
  31711. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  31712. };
  31713. TargetCamera.prototype._updatePosition = function () {
  31714. if (this.parent) {
  31715. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  31716. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  31717. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  31718. return;
  31719. }
  31720. this.position.addInPlace(this.cameraDirection);
  31721. };
  31722. TargetCamera.prototype._checkInputs = function () {
  31723. var needToMove = this._decideIfNeedsToMove();
  31724. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  31725. // Move
  31726. if (needToMove) {
  31727. this._updatePosition();
  31728. }
  31729. // Rotate
  31730. if (needToRotate) {
  31731. this.rotation.x += this.cameraRotation.x;
  31732. this.rotation.y += this.cameraRotation.y;
  31733. //rotate, if quaternion is set and rotation was used
  31734. if (this.rotationQuaternion) {
  31735. var len = this.rotation.lengthSquared();
  31736. if (len) {
  31737. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31738. }
  31739. }
  31740. if (!this.noRotationConstraint) {
  31741. var limit = (Math.PI / 2) * 0.95;
  31742. if (this.rotation.x > limit)
  31743. this.rotation.x = limit;
  31744. if (this.rotation.x < -limit)
  31745. this.rotation.x = -limit;
  31746. }
  31747. }
  31748. // Inertia
  31749. if (needToMove) {
  31750. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  31751. this.cameraDirection.x = 0;
  31752. }
  31753. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  31754. this.cameraDirection.y = 0;
  31755. }
  31756. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  31757. this.cameraDirection.z = 0;
  31758. }
  31759. this.cameraDirection.scaleInPlace(this.inertia);
  31760. }
  31761. if (needToRotate) {
  31762. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  31763. this.cameraRotation.x = 0;
  31764. }
  31765. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  31766. this.cameraRotation.y = 0;
  31767. }
  31768. this.cameraRotation.scaleInPlace(this.inertia);
  31769. }
  31770. _super.prototype._checkInputs.call(this);
  31771. };
  31772. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  31773. if (this.rotationQuaternion) {
  31774. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  31775. //update the up vector!
  31776. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  31777. }
  31778. else {
  31779. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  31780. }
  31781. };
  31782. TargetCamera.prototype._getViewMatrix = function () {
  31783. if (!this.lockedTarget) {
  31784. // Compute
  31785. this._updateCameraRotationMatrix();
  31786. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  31787. // Computing target and final matrix
  31788. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  31789. }
  31790. else {
  31791. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  31792. }
  31793. if (this.getScene().useRightHandedSystem) {
  31794. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31795. }
  31796. else {
  31797. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31798. }
  31799. return this._viewMatrix;
  31800. };
  31801. /**
  31802. * @override
  31803. * Override Camera.createRigCamera
  31804. */
  31805. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31806. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  31807. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  31808. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  31809. if (!this.rotationQuaternion) {
  31810. this.rotationQuaternion = new BABYLON.Quaternion();
  31811. }
  31812. rigCamera._cameraRigParams = {};
  31813. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  31814. }
  31815. return rigCamera;
  31816. }
  31817. return null;
  31818. };
  31819. /**
  31820. * @override
  31821. * Override Camera._updateRigCameras
  31822. */
  31823. TargetCamera.prototype._updateRigCameras = function () {
  31824. var camLeft = this._rigCameras[0];
  31825. var camRight = this._rigCameras[1];
  31826. switch (this.cameraRigMode) {
  31827. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31828. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31829. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31830. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31831. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  31832. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  31833. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  31834. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  31835. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  31836. camLeft.setTarget(this.getTarget());
  31837. camRight.setTarget(this.getTarget());
  31838. break;
  31839. case BABYLON.Camera.RIG_MODE_VR:
  31840. if (camLeft.rotationQuaternion) {
  31841. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31842. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31843. }
  31844. else {
  31845. camLeft.rotation.copyFrom(this.rotation);
  31846. camRight.rotation.copyFrom(this.rotation);
  31847. }
  31848. camLeft.position.copyFrom(this.position);
  31849. camRight.position.copyFrom(this.position);
  31850. break;
  31851. }
  31852. _super.prototype._updateRigCameras.call(this);
  31853. };
  31854. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  31855. if (!this._rigCamTransformMatrix) {
  31856. this._rigCamTransformMatrix = new BABYLON.Matrix();
  31857. }
  31858. var target = this.getTarget();
  31859. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  31860. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  31861. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  31862. };
  31863. TargetCamera.prototype.getClassName = function () {
  31864. return "TargetCamera";
  31865. };
  31866. __decorate([
  31867. BABYLON.serializeAsVector3()
  31868. ], TargetCamera.prototype, "rotation", void 0);
  31869. __decorate([
  31870. BABYLON.serialize()
  31871. ], TargetCamera.prototype, "speed", void 0);
  31872. __decorate([
  31873. BABYLON.serializeAsMeshReference("lockedTargetId")
  31874. ], TargetCamera.prototype, "lockedTarget", void 0);
  31875. return TargetCamera;
  31876. }(BABYLON.Camera));
  31877. BABYLON.TargetCamera = TargetCamera;
  31878. })(BABYLON || (BABYLON = {}));
  31879. //# sourceMappingURL=babylon.targetCamera.js.map
  31880. var BABYLON;
  31881. (function (BABYLON) {
  31882. var ArcRotateCameraKeyboardMoveInput = (function () {
  31883. function ArcRotateCameraKeyboardMoveInput() {
  31884. this._keys = [];
  31885. this.keysUp = [38];
  31886. this.keysDown = [40];
  31887. this.keysLeft = [37];
  31888. this.keysRight = [39];
  31889. this.keysReset = [111];
  31890. this.panningSensibility = 50.0;
  31891. }
  31892. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  31893. var _this = this;
  31894. if (this._onCanvasBlurObserver) {
  31895. return;
  31896. }
  31897. this._scene = this.camera.getScene();
  31898. this._engine = this._scene.getEngine();
  31899. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  31900. _this._keys = [];
  31901. });
  31902. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  31903. var evt = info.event;
  31904. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  31905. _this._ctrlPressed = evt.ctrlKey;
  31906. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31907. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31908. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31909. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  31910. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  31911. var index = _this._keys.indexOf(evt.keyCode);
  31912. if (index === -1) {
  31913. _this._keys.push(evt.keyCode);
  31914. }
  31915. if (evt.preventDefault) {
  31916. if (!noPreventDefault) {
  31917. evt.preventDefault();
  31918. }
  31919. }
  31920. }
  31921. }
  31922. else {
  31923. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31924. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31925. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31926. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  31927. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  31928. var index = _this._keys.indexOf(evt.keyCode);
  31929. if (index >= 0) {
  31930. _this._keys.splice(index, 1);
  31931. }
  31932. if (evt.preventDefault) {
  31933. if (!noPreventDefault) {
  31934. evt.preventDefault();
  31935. }
  31936. }
  31937. }
  31938. }
  31939. });
  31940. };
  31941. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  31942. if (this._scene) {
  31943. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  31944. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  31945. this._onKeyboardObserver = null;
  31946. this._onCanvasBlurObserver = null;
  31947. }
  31948. this._keys = [];
  31949. };
  31950. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  31951. if (this._onKeyboardObserver) {
  31952. var camera = this.camera;
  31953. for (var index = 0; index < this._keys.length; index++) {
  31954. var keyCode = this._keys[index];
  31955. if (this.keysLeft.indexOf(keyCode) !== -1) {
  31956. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31957. camera.inertialPanningX -= 1 / this.panningSensibility;
  31958. }
  31959. else {
  31960. camera.inertialAlphaOffset -= 0.01;
  31961. }
  31962. }
  31963. else if (this.keysUp.indexOf(keyCode) !== -1) {
  31964. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31965. camera.inertialPanningY += 1 / this.panningSensibility;
  31966. }
  31967. else {
  31968. camera.inertialBetaOffset -= 0.01;
  31969. }
  31970. }
  31971. else if (this.keysRight.indexOf(keyCode) !== -1) {
  31972. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31973. camera.inertialPanningX += 1 / this.panningSensibility;
  31974. }
  31975. else {
  31976. camera.inertialAlphaOffset += 0.01;
  31977. }
  31978. }
  31979. else if (this.keysDown.indexOf(keyCode) !== -1) {
  31980. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31981. camera.inertialPanningY -= 1 / this.panningSensibility;
  31982. }
  31983. else {
  31984. camera.inertialBetaOffset += 0.01;
  31985. }
  31986. }
  31987. else if (this.keysReset.indexOf(keyCode) !== -1) {
  31988. camera.restoreState();
  31989. }
  31990. }
  31991. }
  31992. };
  31993. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  31994. return "ArcRotateCameraKeyboardMoveInput";
  31995. };
  31996. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  31997. return "keyboard";
  31998. };
  31999. __decorate([
  32000. BABYLON.serialize()
  32001. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  32002. __decorate([
  32003. BABYLON.serialize()
  32004. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  32005. __decorate([
  32006. BABYLON.serialize()
  32007. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  32008. __decorate([
  32009. BABYLON.serialize()
  32010. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  32011. __decorate([
  32012. BABYLON.serialize()
  32013. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  32014. __decorate([
  32015. BABYLON.serialize()
  32016. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  32017. return ArcRotateCameraKeyboardMoveInput;
  32018. }());
  32019. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  32020. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  32021. })(BABYLON || (BABYLON = {}));
  32022. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  32023. var BABYLON;
  32024. (function (BABYLON) {
  32025. var ArcRotateCameraMouseWheelInput = (function () {
  32026. function ArcRotateCameraMouseWheelInput() {
  32027. this.wheelPrecision = 3.0;
  32028. }
  32029. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  32030. var _this = this;
  32031. this._wheel = function (p, s) {
  32032. //sanity check - this should be a PointerWheel event.
  32033. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  32034. return;
  32035. var event = p.event;
  32036. var delta = 0;
  32037. if (event.wheelDelta) {
  32038. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  32039. }
  32040. else if (event.detail) {
  32041. delta = -event.detail / _this.wheelPrecision;
  32042. }
  32043. if (delta)
  32044. _this.camera.inertialRadiusOffset += delta;
  32045. if (event.preventDefault) {
  32046. if (!noPreventDefault) {
  32047. event.preventDefault();
  32048. }
  32049. }
  32050. };
  32051. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  32052. };
  32053. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  32054. if (this._observer && element) {
  32055. this.camera.getScene().onPointerObservable.remove(this._observer);
  32056. this._observer = null;
  32057. this._wheel = null;
  32058. }
  32059. };
  32060. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  32061. return "ArcRotateCameraMouseWheelInput";
  32062. };
  32063. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  32064. return "mousewheel";
  32065. };
  32066. __decorate([
  32067. BABYLON.serialize()
  32068. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  32069. return ArcRotateCameraMouseWheelInput;
  32070. }());
  32071. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  32072. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  32073. })(BABYLON || (BABYLON = {}));
  32074. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  32075. var BABYLON;
  32076. (function (BABYLON) {
  32077. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  32078. var ArcRotateCameraPointersInput = (function () {
  32079. function ArcRotateCameraPointersInput() {
  32080. this.buttons = [0, 1, 2];
  32081. this.angularSensibilityX = 1000.0;
  32082. this.angularSensibilityY = 1000.0;
  32083. this.pinchPrecision = 6.0;
  32084. this.panningSensibility = 50.0;
  32085. this._isPanClick = false;
  32086. this.pinchInwards = true;
  32087. }
  32088. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  32089. var _this = this;
  32090. var engine = this.camera.getEngine();
  32091. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  32092. var pointA, pointB;
  32093. var previousPinchDistance = 0;
  32094. this._pointerInput = function (p, s) {
  32095. var evt = p.event;
  32096. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  32097. return;
  32098. }
  32099. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  32100. try {
  32101. evt.srcElement.setPointerCapture(evt.pointerId);
  32102. }
  32103. catch (e) {
  32104. //Nothing to do with the error. Execution will continue.
  32105. }
  32106. // Manage panning with pan button click
  32107. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  32108. // manage pointers
  32109. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  32110. if (pointA === undefined) {
  32111. pointA = cacheSoloPointer;
  32112. }
  32113. else if (pointB === undefined) {
  32114. pointB = cacheSoloPointer;
  32115. }
  32116. if (!noPreventDefault) {
  32117. evt.preventDefault();
  32118. element.focus();
  32119. }
  32120. }
  32121. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  32122. _this.camera.restoreState();
  32123. }
  32124. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  32125. try {
  32126. evt.srcElement.releasePointerCapture(evt.pointerId);
  32127. }
  32128. catch (e) {
  32129. //Nothing to do with the error.
  32130. }
  32131. cacheSoloPointer = null;
  32132. previousPinchDistance = 0;
  32133. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  32134. //but emptying completly pointers collection is required to fix a bug on iPhone :
  32135. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  32136. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  32137. pointA = pointB = undefined;
  32138. if (!noPreventDefault) {
  32139. evt.preventDefault();
  32140. }
  32141. }
  32142. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  32143. if (!noPreventDefault) {
  32144. evt.preventDefault();
  32145. }
  32146. // One button down
  32147. if (pointA && pointB === undefined) {
  32148. if (_this.panningSensibility !== 0 &&
  32149. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  32150. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  32151. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  32152. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  32153. }
  32154. else {
  32155. var offsetX = evt.clientX - cacheSoloPointer.x;
  32156. var offsetY = evt.clientY - cacheSoloPointer.y;
  32157. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32158. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32159. }
  32160. cacheSoloPointer.x = evt.clientX;
  32161. cacheSoloPointer.y = evt.clientY;
  32162. }
  32163. else if (pointA && pointB) {
  32164. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  32165. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  32166. ed.x = evt.clientX;
  32167. ed.y = evt.clientY;
  32168. var direction = _this.pinchInwards ? 1 : -1;
  32169. var distX = pointA.x - pointB.x;
  32170. var distY = pointA.y - pointB.y;
  32171. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  32172. if (previousPinchDistance === 0) {
  32173. previousPinchDistance = pinchSquaredDistance;
  32174. return;
  32175. }
  32176. if (pinchSquaredDistance !== previousPinchDistance) {
  32177. _this.camera
  32178. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  32179. (_this.pinchPrecision *
  32180. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  32181. direction);
  32182. previousPinchDistance = pinchSquaredDistance;
  32183. }
  32184. }
  32185. }
  32186. };
  32187. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  32188. this._onContextMenu = function (evt) {
  32189. evt.preventDefault();
  32190. };
  32191. if (!this.camera._useCtrlForPanning) {
  32192. element.addEventListener("contextmenu", this._onContextMenu, false);
  32193. }
  32194. this._onLostFocus = function () {
  32195. //this._keys = [];
  32196. pointA = pointB = undefined;
  32197. previousPinchDistance = 0;
  32198. cacheSoloPointer = null;
  32199. };
  32200. this._onMouseMove = function (evt) {
  32201. if (!engine.isPointerLock) {
  32202. return;
  32203. }
  32204. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  32205. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  32206. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32207. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32208. if (!noPreventDefault) {
  32209. evt.preventDefault();
  32210. }
  32211. };
  32212. this._onGestureStart = function (e) {
  32213. if (window.MSGesture === undefined) {
  32214. return;
  32215. }
  32216. if (!_this._MSGestureHandler) {
  32217. _this._MSGestureHandler = new MSGesture();
  32218. _this._MSGestureHandler.target = element;
  32219. }
  32220. _this._MSGestureHandler.addPointer(e.pointerId);
  32221. };
  32222. this._onGesture = function (e) {
  32223. _this.camera.radius *= e.scale;
  32224. if (e.preventDefault) {
  32225. if (!noPreventDefault) {
  32226. e.stopPropagation();
  32227. e.preventDefault();
  32228. }
  32229. }
  32230. };
  32231. element.addEventListener("mousemove", this._onMouseMove, false);
  32232. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  32233. element.addEventListener("MSGestureChange", this._onGesture, false);
  32234. BABYLON.Tools.RegisterTopRootEvents([
  32235. { name: "blur", handler: this._onLostFocus }
  32236. ]);
  32237. };
  32238. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  32239. BABYLON.Tools.UnregisterTopRootEvents([
  32240. { name: "blur", handler: this._onLostFocus }
  32241. ]);
  32242. if (element && this._observer) {
  32243. this.camera.getScene().onPointerObservable.remove(this._observer);
  32244. this._observer = null;
  32245. element.removeEventListener("contextmenu", this._onContextMenu);
  32246. element.removeEventListener("mousemove", this._onMouseMove);
  32247. element.removeEventListener("MSPointerDown", this._onGestureStart);
  32248. element.removeEventListener("MSGestureChange", this._onGesture);
  32249. this._isPanClick = false;
  32250. this.pinchInwards = true;
  32251. this._onMouseMove = null;
  32252. this._onGestureStart = null;
  32253. this._onGesture = null;
  32254. this._MSGestureHandler = null;
  32255. this._onLostFocus = null;
  32256. this._onContextMenu = null;
  32257. }
  32258. };
  32259. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  32260. return "ArcRotateCameraPointersInput";
  32261. };
  32262. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  32263. return "pointers";
  32264. };
  32265. __decorate([
  32266. BABYLON.serialize()
  32267. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  32268. __decorate([
  32269. BABYLON.serialize()
  32270. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  32271. __decorate([
  32272. BABYLON.serialize()
  32273. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  32274. __decorate([
  32275. BABYLON.serialize()
  32276. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  32277. __decorate([
  32278. BABYLON.serialize()
  32279. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  32280. return ArcRotateCameraPointersInput;
  32281. }());
  32282. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  32283. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  32284. })(BABYLON || (BABYLON = {}));
  32285. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  32286. /// <reference path="babylon.targetCamera.ts" />
  32287. /// <reference path="..\Tools\babylon.tools.ts" />
  32288. var BABYLON;
  32289. (function (BABYLON) {
  32290. var ArcRotateCamera = (function (_super) {
  32291. __extends(ArcRotateCamera, _super);
  32292. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  32293. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  32294. _this.inertialAlphaOffset = 0;
  32295. _this.inertialBetaOffset = 0;
  32296. _this.inertialRadiusOffset = 0;
  32297. _this.lowerAlphaLimit = null;
  32298. _this.upperAlphaLimit = null;
  32299. _this.lowerBetaLimit = 0.01;
  32300. _this.upperBetaLimit = Math.PI;
  32301. _this.lowerRadiusLimit = null;
  32302. _this.upperRadiusLimit = null;
  32303. _this.inertialPanningX = 0;
  32304. _this.inertialPanningY = 0;
  32305. _this.panningInertia = 0.9;
  32306. //-- end properties for backward compatibility for inputs
  32307. _this.zoomOnFactor = 1;
  32308. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  32309. _this.allowUpsideDown = true;
  32310. _this._viewMatrix = new BABYLON.Matrix();
  32311. // Panning
  32312. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  32313. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  32314. _this.checkCollisions = false;
  32315. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  32316. _this._previousPosition = BABYLON.Vector3.Zero();
  32317. _this._collisionVelocity = BABYLON.Vector3.Zero();
  32318. _this._newPosition = BABYLON.Vector3.Zero();
  32319. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32320. if (collidedMesh === void 0) { collidedMesh = null; }
  32321. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  32322. newPosition.multiplyInPlace(_this._collider.radius);
  32323. }
  32324. if (!collidedMesh) {
  32325. _this._previousPosition.copyFrom(_this.position);
  32326. }
  32327. else {
  32328. _this.setPosition(newPosition);
  32329. if (_this.onCollide) {
  32330. _this.onCollide(collidedMesh);
  32331. }
  32332. }
  32333. // Recompute because of constraints
  32334. var cosa = Math.cos(_this.alpha);
  32335. var sina = Math.sin(_this.alpha);
  32336. var cosb = Math.cos(_this.beta);
  32337. var sinb = Math.sin(_this.beta);
  32338. if (sinb === 0) {
  32339. sinb = 0.0001;
  32340. }
  32341. var target = _this._getTargetPosition();
  32342. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  32343. _this.position.copyFrom(_this._newPosition);
  32344. var up = _this.upVector;
  32345. if (_this.allowUpsideDown && _this.beta < 0) {
  32346. up = up.clone();
  32347. up = up.negate();
  32348. }
  32349. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  32350. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  32351. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  32352. _this._collisionTriggered = false;
  32353. };
  32354. _this._target = BABYLON.Vector3.Zero();
  32355. if (target) {
  32356. _this.setTarget(target);
  32357. }
  32358. _this.alpha = alpha;
  32359. _this.beta = beta;
  32360. _this.radius = radius;
  32361. _this.getViewMatrix();
  32362. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  32363. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  32364. return _this;
  32365. }
  32366. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  32367. get: function () {
  32368. return this._target;
  32369. },
  32370. set: function (value) {
  32371. this.setTarget(value);
  32372. },
  32373. enumerable: true,
  32374. configurable: true
  32375. });
  32376. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  32377. //-- begin properties for backward compatibility for inputs
  32378. get: function () {
  32379. var pointers = this.inputs.attached["pointers"];
  32380. if (pointers)
  32381. return pointers.angularSensibilityX;
  32382. },
  32383. set: function (value) {
  32384. var pointers = this.inputs.attached["pointers"];
  32385. if (pointers) {
  32386. pointers.angularSensibilityX = value;
  32387. }
  32388. },
  32389. enumerable: true,
  32390. configurable: true
  32391. });
  32392. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  32393. get: function () {
  32394. var pointers = this.inputs.attached["pointers"];
  32395. if (pointers)
  32396. return pointers.angularSensibilityY;
  32397. },
  32398. set: function (value) {
  32399. var pointers = this.inputs.attached["pointers"];
  32400. if (pointers) {
  32401. pointers.angularSensibilityY = value;
  32402. }
  32403. },
  32404. enumerable: true,
  32405. configurable: true
  32406. });
  32407. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  32408. get: function () {
  32409. var pointers = this.inputs.attached["pointers"];
  32410. if (pointers)
  32411. return pointers.pinchPrecision;
  32412. },
  32413. set: function (value) {
  32414. var pointers = this.inputs.attached["pointers"];
  32415. if (pointers) {
  32416. pointers.pinchPrecision = value;
  32417. }
  32418. },
  32419. enumerable: true,
  32420. configurable: true
  32421. });
  32422. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  32423. get: function () {
  32424. var pointers = this.inputs.attached["pointers"];
  32425. if (pointers)
  32426. return pointers.panningSensibility;
  32427. },
  32428. set: function (value) {
  32429. var pointers = this.inputs.attached["pointers"];
  32430. if (pointers) {
  32431. pointers.panningSensibility = value;
  32432. }
  32433. },
  32434. enumerable: true,
  32435. configurable: true
  32436. });
  32437. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  32438. get: function () {
  32439. var keyboard = this.inputs.attached["keyboard"];
  32440. if (keyboard)
  32441. return keyboard.keysUp;
  32442. },
  32443. set: function (value) {
  32444. var keyboard = this.inputs.attached["keyboard"];
  32445. if (keyboard)
  32446. keyboard.keysUp = value;
  32447. },
  32448. enumerable: true,
  32449. configurable: true
  32450. });
  32451. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  32452. get: function () {
  32453. var keyboard = this.inputs.attached["keyboard"];
  32454. if (keyboard)
  32455. return keyboard.keysDown;
  32456. },
  32457. set: function (value) {
  32458. var keyboard = this.inputs.attached["keyboard"];
  32459. if (keyboard)
  32460. keyboard.keysDown = value;
  32461. },
  32462. enumerable: true,
  32463. configurable: true
  32464. });
  32465. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  32466. get: function () {
  32467. var keyboard = this.inputs.attached["keyboard"];
  32468. if (keyboard)
  32469. return keyboard.keysLeft;
  32470. },
  32471. set: function (value) {
  32472. var keyboard = this.inputs.attached["keyboard"];
  32473. if (keyboard)
  32474. keyboard.keysLeft = value;
  32475. },
  32476. enumerable: true,
  32477. configurable: true
  32478. });
  32479. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  32480. get: function () {
  32481. var keyboard = this.inputs.attached["keyboard"];
  32482. if (keyboard)
  32483. return keyboard.keysRight;
  32484. },
  32485. set: function (value) {
  32486. var keyboard = this.inputs.attached["keyboard"];
  32487. if (keyboard)
  32488. keyboard.keysRight = value;
  32489. },
  32490. enumerable: true,
  32491. configurable: true
  32492. });
  32493. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  32494. get: function () {
  32495. var mousewheel = this.inputs.attached["mousewheel"];
  32496. if (mousewheel)
  32497. return mousewheel.wheelPrecision;
  32498. },
  32499. set: function (value) {
  32500. var mousewheel = this.inputs.attached["mousewheel"];
  32501. if (mousewheel)
  32502. mousewheel.wheelPrecision = value;
  32503. },
  32504. enumerable: true,
  32505. configurable: true
  32506. });
  32507. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  32508. get: function () {
  32509. return this._bouncingBehavior;
  32510. },
  32511. enumerable: true,
  32512. configurable: true
  32513. });
  32514. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  32515. get: function () {
  32516. return this._bouncingBehavior != null;
  32517. },
  32518. set: function (value) {
  32519. if (value === this.useBouncingBehavior) {
  32520. return;
  32521. }
  32522. if (value) {
  32523. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  32524. this.addBehavior(this._bouncingBehavior);
  32525. }
  32526. else {
  32527. this.removeBehavior(this._bouncingBehavior);
  32528. this._bouncingBehavior = null;
  32529. }
  32530. },
  32531. enumerable: true,
  32532. configurable: true
  32533. });
  32534. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  32535. get: function () {
  32536. return this._framingBehavior;
  32537. },
  32538. enumerable: true,
  32539. configurable: true
  32540. });
  32541. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  32542. get: function () {
  32543. return this._framingBehavior != null;
  32544. },
  32545. set: function (value) {
  32546. if (value === this.useFramingBehavior) {
  32547. return;
  32548. }
  32549. if (value) {
  32550. this._framingBehavior = new BABYLON.FramingBehavior();
  32551. this.addBehavior(this._framingBehavior);
  32552. }
  32553. else {
  32554. this.removeBehavior(this._framingBehavior);
  32555. this._framingBehavior = null;
  32556. }
  32557. },
  32558. enumerable: true,
  32559. configurable: true
  32560. });
  32561. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  32562. get: function () {
  32563. return this._autoRotationBehavior;
  32564. },
  32565. enumerable: true,
  32566. configurable: true
  32567. });
  32568. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  32569. get: function () {
  32570. return this._autoRotationBehavior != null;
  32571. },
  32572. set: function (value) {
  32573. if (value === this.useAutoRotationBehavior) {
  32574. return;
  32575. }
  32576. if (value) {
  32577. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  32578. this.addBehavior(this._autoRotationBehavior);
  32579. }
  32580. else {
  32581. this.removeBehavior(this._autoRotationBehavior);
  32582. this._autoRotationBehavior = null;
  32583. }
  32584. },
  32585. enumerable: true,
  32586. configurable: true
  32587. });
  32588. // Cache
  32589. ArcRotateCamera.prototype._initCache = function () {
  32590. _super.prototype._initCache.call(this);
  32591. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32592. this._cache.alpha = undefined;
  32593. this._cache.beta = undefined;
  32594. this._cache.radius = undefined;
  32595. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  32596. };
  32597. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  32598. if (!ignoreParentClass) {
  32599. _super.prototype._updateCache.call(this);
  32600. }
  32601. this._cache._target.copyFrom(this._getTargetPosition());
  32602. this._cache.alpha = this.alpha;
  32603. this._cache.beta = this.beta;
  32604. this._cache.radius = this.radius;
  32605. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  32606. };
  32607. ArcRotateCamera.prototype._getTargetPosition = function () {
  32608. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  32609. var pos = this._targetHost.getAbsolutePosition();
  32610. if (this._targetBoundingCenter) {
  32611. pos.addToRef(this._targetBoundingCenter, this._target);
  32612. }
  32613. else {
  32614. this._target.copyFrom(pos);
  32615. }
  32616. }
  32617. var lockedTargetPosition = this._getLockedTargetPosition();
  32618. if (lockedTargetPosition) {
  32619. return lockedTargetPosition;
  32620. }
  32621. return this._target;
  32622. };
  32623. ArcRotateCamera.prototype.storeState = function () {
  32624. this._storedAlpha = this.alpha;
  32625. this._storedBeta = this.beta;
  32626. this._storedRadius = this.radius;
  32627. this._storedTarget = this._getTargetPosition().clone();
  32628. return _super.prototype.storeState.call(this);
  32629. };
  32630. /**
  32631. * Restored camera state. You must call storeState() first
  32632. */
  32633. ArcRotateCamera.prototype.restoreState = function () {
  32634. if (!_super.prototype.restoreState.call(this)) {
  32635. return false;
  32636. }
  32637. this.alpha = this._storedAlpha;
  32638. this.beta = this._storedBeta;
  32639. this.radius = this._storedRadius;
  32640. this.setTarget(this._storedTarget);
  32641. this.inertialAlphaOffset = 0;
  32642. this.inertialBetaOffset = 0;
  32643. this.inertialRadiusOffset = 0;
  32644. this.inertialPanningX = 0;
  32645. this.inertialPanningY = 0;
  32646. return true;
  32647. };
  32648. // Synchronized
  32649. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  32650. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  32651. return false;
  32652. return this._cache._target.equals(this._getTargetPosition())
  32653. && this._cache.alpha === this.alpha
  32654. && this._cache.beta === this.beta
  32655. && this._cache.radius === this.radius
  32656. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  32657. };
  32658. // Methods
  32659. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  32660. var _this = this;
  32661. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  32662. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  32663. this._useCtrlForPanning = useCtrlForPanning;
  32664. this._panningMouseButton = panningMouseButton;
  32665. this.inputs.attachElement(element, noPreventDefault);
  32666. this._reset = function () {
  32667. _this.inertialAlphaOffset = 0;
  32668. _this.inertialBetaOffset = 0;
  32669. _this.inertialRadiusOffset = 0;
  32670. _this.inertialPanningX = 0;
  32671. _this.inertialPanningY = 0;
  32672. };
  32673. };
  32674. ArcRotateCamera.prototype.detachControl = function (element) {
  32675. this.inputs.detachElement(element);
  32676. if (this._reset) {
  32677. this._reset();
  32678. }
  32679. };
  32680. ArcRotateCamera.prototype._checkInputs = function () {
  32681. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  32682. if (this._collisionTriggered) {
  32683. return;
  32684. }
  32685. this.inputs.checkInputs();
  32686. // Inertia
  32687. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  32688. if (this.getScene().useRightHandedSystem) {
  32689. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32690. }
  32691. else {
  32692. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32693. }
  32694. this.beta += this.inertialBetaOffset;
  32695. this.radius -= this.inertialRadiusOffset;
  32696. this.inertialAlphaOffset *= this.inertia;
  32697. this.inertialBetaOffset *= this.inertia;
  32698. this.inertialRadiusOffset *= this.inertia;
  32699. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  32700. this.inertialAlphaOffset = 0;
  32701. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  32702. this.inertialBetaOffset = 0;
  32703. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  32704. this.inertialRadiusOffset = 0;
  32705. }
  32706. // Panning inertia
  32707. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  32708. if (!this._localDirection) {
  32709. this._localDirection = BABYLON.Vector3.Zero();
  32710. this._transformedDirection = BABYLON.Vector3.Zero();
  32711. }
  32712. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  32713. this._localDirection.multiplyInPlace(this.panningAxis);
  32714. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  32715. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  32716. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  32717. if (!this.panningAxis.y) {
  32718. this._transformedDirection.y = 0;
  32719. }
  32720. if (!this._targetHost) {
  32721. this._target.addInPlace(this._transformedDirection);
  32722. }
  32723. this.inertialPanningX *= this.panningInertia;
  32724. this.inertialPanningY *= this.panningInertia;
  32725. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  32726. this.inertialPanningX = 0;
  32727. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  32728. this.inertialPanningY = 0;
  32729. }
  32730. // Limits
  32731. this._checkLimits();
  32732. _super.prototype._checkInputs.call(this);
  32733. };
  32734. ArcRotateCamera.prototype._checkLimits = function () {
  32735. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  32736. if (this.allowUpsideDown && this.beta > Math.PI) {
  32737. this.beta = this.beta - (2 * Math.PI);
  32738. }
  32739. }
  32740. else {
  32741. if (this.beta < this.lowerBetaLimit) {
  32742. this.beta = this.lowerBetaLimit;
  32743. }
  32744. }
  32745. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  32746. if (this.allowUpsideDown && this.beta < -Math.PI) {
  32747. this.beta = this.beta + (2 * Math.PI);
  32748. }
  32749. }
  32750. else {
  32751. if (this.beta > this.upperBetaLimit) {
  32752. this.beta = this.upperBetaLimit;
  32753. }
  32754. }
  32755. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  32756. this.alpha = this.lowerAlphaLimit;
  32757. }
  32758. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  32759. this.alpha = this.upperAlphaLimit;
  32760. }
  32761. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  32762. this.radius = this.lowerRadiusLimit;
  32763. }
  32764. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  32765. this.radius = this.upperRadiusLimit;
  32766. }
  32767. };
  32768. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  32769. var radiusv3 = this.position.subtract(this._getTargetPosition());
  32770. this.radius = radiusv3.length();
  32771. if (this.radius === 0) {
  32772. this.radius = 0.0001; // Just to avoid division by zero
  32773. }
  32774. // Alpha
  32775. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  32776. if (radiusv3.z < 0) {
  32777. this.alpha = 2 * Math.PI - this.alpha;
  32778. }
  32779. // Beta
  32780. this.beta = Math.acos(radiusv3.y / this.radius);
  32781. this._checkLimits();
  32782. };
  32783. ArcRotateCamera.prototype.setPosition = function (position) {
  32784. if (this.position.equals(position)) {
  32785. return;
  32786. }
  32787. this.position.copyFrom(position);
  32788. this.rebuildAnglesAndRadius();
  32789. };
  32790. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  32791. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  32792. if (allowSamePosition === void 0) { allowSamePosition = false; }
  32793. if (target.getBoundingInfo) {
  32794. if (toBoundingCenter) {
  32795. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  32796. }
  32797. else {
  32798. this._targetBoundingCenter = null;
  32799. }
  32800. this._targetHost = target;
  32801. this._target = this._getTargetPosition();
  32802. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  32803. }
  32804. else {
  32805. var newTarget = target;
  32806. var currentTarget = this._getTargetPosition();
  32807. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  32808. return;
  32809. }
  32810. this._targetHost = null;
  32811. this._target = newTarget;
  32812. this._targetBoundingCenter = null;
  32813. this.onMeshTargetChangedObservable.notifyObservers(null);
  32814. }
  32815. this.rebuildAnglesAndRadius();
  32816. };
  32817. ArcRotateCamera.prototype._getViewMatrix = function () {
  32818. // Compute
  32819. var cosa = Math.cos(this.alpha);
  32820. var sina = Math.sin(this.alpha);
  32821. var cosb = Math.cos(this.beta);
  32822. var sinb = Math.sin(this.beta);
  32823. if (sinb === 0) {
  32824. sinb = 0.0001;
  32825. }
  32826. var target = this._getTargetPosition();
  32827. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  32828. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  32829. if (!this._collider) {
  32830. this._collider = new BABYLON.Collider();
  32831. }
  32832. this._collider.radius = this.collisionRadius;
  32833. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  32834. this._collisionTriggered = true;
  32835. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32836. }
  32837. else {
  32838. this.position.copyFrom(this._newPosition);
  32839. var up = this.upVector;
  32840. if (this.allowUpsideDown && sinb < 0) {
  32841. up = up.clone();
  32842. up = up.negate();
  32843. }
  32844. if (this.getScene().useRightHandedSystem) {
  32845. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  32846. }
  32847. else {
  32848. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  32849. }
  32850. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  32851. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  32852. }
  32853. this._currentTarget = target;
  32854. return this._viewMatrix;
  32855. };
  32856. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  32857. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32858. meshes = meshes || this.getScene().meshes;
  32859. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  32860. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  32861. this.radius = distance * this.zoomOnFactor;
  32862. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  32863. };
  32864. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  32865. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32866. var meshesOrMinMaxVector;
  32867. var distance;
  32868. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  32869. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  32870. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  32871. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  32872. }
  32873. else {
  32874. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  32875. distance = meshesOrMinMaxVectorAndDistance.distance;
  32876. }
  32877. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  32878. if (!doNotUpdateMaxZ) {
  32879. this.maxZ = distance * 2;
  32880. }
  32881. };
  32882. /**
  32883. * @override
  32884. * Override Camera.createRigCamera
  32885. */
  32886. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32887. var alphaShift;
  32888. switch (this.cameraRigMode) {
  32889. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32890. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32891. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32892. case BABYLON.Camera.RIG_MODE_VR:
  32893. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  32894. break;
  32895. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32896. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  32897. break;
  32898. }
  32899. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  32900. rigCam._cameraRigParams = {};
  32901. return rigCam;
  32902. };
  32903. /**
  32904. * @override
  32905. * Override Camera._updateRigCameras
  32906. */
  32907. ArcRotateCamera.prototype._updateRigCameras = function () {
  32908. var camLeft = this._rigCameras[0];
  32909. var camRight = this._rigCameras[1];
  32910. camLeft.beta = camRight.beta = this.beta;
  32911. camLeft.radius = camRight.radius = this.radius;
  32912. switch (this.cameraRigMode) {
  32913. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32914. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32915. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32916. case BABYLON.Camera.RIG_MODE_VR:
  32917. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32918. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32919. break;
  32920. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32921. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32922. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32923. break;
  32924. }
  32925. _super.prototype._updateRigCameras.call(this);
  32926. };
  32927. ArcRotateCamera.prototype.dispose = function () {
  32928. this.inputs.clear();
  32929. _super.prototype.dispose.call(this);
  32930. };
  32931. ArcRotateCamera.prototype.getClassName = function () {
  32932. return "ArcRotateCamera";
  32933. };
  32934. __decorate([
  32935. BABYLON.serialize()
  32936. ], ArcRotateCamera.prototype, "alpha", void 0);
  32937. __decorate([
  32938. BABYLON.serialize()
  32939. ], ArcRotateCamera.prototype, "beta", void 0);
  32940. __decorate([
  32941. BABYLON.serialize()
  32942. ], ArcRotateCamera.prototype, "radius", void 0);
  32943. __decorate([
  32944. BABYLON.serializeAsVector3("target")
  32945. ], ArcRotateCamera.prototype, "_target", void 0);
  32946. __decorate([
  32947. BABYLON.serialize()
  32948. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  32949. __decorate([
  32950. BABYLON.serialize()
  32951. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  32952. __decorate([
  32953. BABYLON.serialize()
  32954. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  32955. __decorate([
  32956. BABYLON.serialize()
  32957. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  32958. __decorate([
  32959. BABYLON.serialize()
  32960. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  32961. __decorate([
  32962. BABYLON.serialize()
  32963. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  32964. __decorate([
  32965. BABYLON.serialize()
  32966. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  32967. __decorate([
  32968. BABYLON.serialize()
  32969. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  32970. __decorate([
  32971. BABYLON.serialize()
  32972. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  32973. __decorate([
  32974. BABYLON.serialize()
  32975. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  32976. __decorate([
  32977. BABYLON.serialize()
  32978. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  32979. __decorate([
  32980. BABYLON.serialize()
  32981. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  32982. __decorate([
  32983. BABYLON.serialize()
  32984. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  32985. __decorate([
  32986. BABYLON.serialize()
  32987. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  32988. return ArcRotateCamera;
  32989. }(BABYLON.TargetCamera));
  32990. BABYLON.ArcRotateCamera = ArcRotateCamera;
  32991. })(BABYLON || (BABYLON = {}));
  32992. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  32993. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  32994. var BABYLON;
  32995. (function (BABYLON) {
  32996. var ArcRotateCameraInputsManager = (function (_super) {
  32997. __extends(ArcRotateCameraInputsManager, _super);
  32998. function ArcRotateCameraInputsManager(camera) {
  32999. return _super.call(this, camera) || this;
  33000. }
  33001. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  33002. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  33003. return this;
  33004. };
  33005. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  33006. this.add(new BABYLON.ArcRotateCameraPointersInput());
  33007. return this;
  33008. };
  33009. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  33010. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  33011. return this;
  33012. };
  33013. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  33014. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  33015. return this;
  33016. };
  33017. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  33018. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  33019. return this;
  33020. };
  33021. return ArcRotateCameraInputsManager;
  33022. }(BABYLON.CameraInputsManager));
  33023. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  33024. })(BABYLON || (BABYLON = {}));
  33025. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  33026. var BABYLON;
  33027. (function (BABYLON) {
  33028. var CubeTexture = (function (_super) {
  33029. __extends(CubeTexture, _super);
  33030. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  33031. if (onLoad === void 0) { onLoad = null; }
  33032. if (onError === void 0) { onError = null; }
  33033. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  33034. if (prefiltered === void 0) { prefiltered = false; }
  33035. if (forcedExtension === void 0) { forcedExtension = null; }
  33036. var _this = _super.call(this, scene) || this;
  33037. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  33038. _this.name = rootUrl;
  33039. _this.url = rootUrl;
  33040. _this._noMipmap = noMipmap;
  33041. _this.hasAlpha = false;
  33042. _this._format = format;
  33043. _this._prefiltered = prefiltered;
  33044. _this.isCube = true;
  33045. _this._textureMatrix = BABYLON.Matrix.Identity();
  33046. if (prefiltered) {
  33047. _this.gammaSpace = false;
  33048. }
  33049. if (!rootUrl && !files) {
  33050. return _this;
  33051. }
  33052. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  33053. if (!files) {
  33054. if (!extensions) {
  33055. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  33056. }
  33057. files = [];
  33058. for (var index = 0; index < extensions.length; index++) {
  33059. files.push(rootUrl + extensions[index]);
  33060. }
  33061. _this._extensions = extensions;
  33062. }
  33063. _this._files = files;
  33064. if (!_this._texture) {
  33065. if (!scene.useDelayedTextureLoading) {
  33066. if (prefiltered) {
  33067. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  33068. }
  33069. else {
  33070. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  33071. }
  33072. }
  33073. else {
  33074. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33075. }
  33076. }
  33077. else if (onLoad) {
  33078. if (_this._texture.isReady) {
  33079. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  33080. }
  33081. else {
  33082. _this._texture.onLoadedObservable.add(onLoad);
  33083. }
  33084. }
  33085. return _this;
  33086. }
  33087. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  33088. return new CubeTexture("", scene, null, noMipmap, files);
  33089. };
  33090. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  33091. if (forcedExtension === void 0) { forcedExtension = null; }
  33092. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  33093. };
  33094. // Methods
  33095. CubeTexture.prototype.delayLoad = function () {
  33096. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33097. return;
  33098. }
  33099. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33100. this._texture = this._getFromCache(this.url, this._noMipmap);
  33101. if (!this._texture) {
  33102. if (this._prefiltered) {
  33103. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  33104. }
  33105. else {
  33106. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  33107. }
  33108. }
  33109. };
  33110. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  33111. return this._textureMatrix;
  33112. };
  33113. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  33114. this._textureMatrix = value;
  33115. };
  33116. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33117. var texture = BABYLON.SerializationHelper.Parse(function () {
  33118. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  33119. }, parsedTexture, scene);
  33120. // Animations
  33121. if (parsedTexture.animations) {
  33122. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  33123. var parsedAnimation = parsedTexture.animations[animationIndex];
  33124. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33125. }
  33126. }
  33127. return texture;
  33128. };
  33129. CubeTexture.prototype.clone = function () {
  33130. var _this = this;
  33131. return BABYLON.SerializationHelper.Clone(function () {
  33132. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  33133. }, this);
  33134. };
  33135. return CubeTexture;
  33136. }(BABYLON.BaseTexture));
  33137. BABYLON.CubeTexture = CubeTexture;
  33138. })(BABYLON || (BABYLON = {}));
  33139. //# sourceMappingURL=babylon.cubeTexture.js.map
  33140. var BABYLON;
  33141. (function (BABYLON) {
  33142. var RenderTargetTexture = (function (_super) {
  33143. __extends(RenderTargetTexture, _super);
  33144. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  33145. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  33146. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33147. if (isCube === void 0) { isCube = false; }
  33148. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33149. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  33150. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  33151. if (isMulti === void 0) { isMulti = false; }
  33152. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  33153. _this.isCube = isCube;
  33154. /**
  33155. * Use this list to define the list of mesh you want to render.
  33156. */
  33157. _this.renderList = new Array();
  33158. _this.renderParticles = true;
  33159. _this.renderSprites = false;
  33160. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  33161. _this.ignoreCameraViewport = false;
  33162. // Events
  33163. /**
  33164. * An event triggered when the texture is unbind.
  33165. * @type {BABYLON.Observable}
  33166. */
  33167. _this.onBeforeBindObservable = new BABYLON.Observable();
  33168. /**
  33169. * An event triggered when the texture is unbind.
  33170. * @type {BABYLON.Observable}
  33171. */
  33172. _this.onAfterUnbindObservable = new BABYLON.Observable();
  33173. /**
  33174. * An event triggered before rendering the texture
  33175. * @type {BABYLON.Observable}
  33176. */
  33177. _this.onBeforeRenderObservable = new BABYLON.Observable();
  33178. /**
  33179. * An event triggered after rendering the texture
  33180. * @type {BABYLON.Observable}
  33181. */
  33182. _this.onAfterRenderObservable = new BABYLON.Observable();
  33183. /**
  33184. * An event triggered after the texture clear
  33185. * @type {BABYLON.Observable}
  33186. */
  33187. _this.onClearObservable = new BABYLON.Observable();
  33188. _this._currentRefreshId = -1;
  33189. _this._refreshRate = 1;
  33190. _this._samples = 1;
  33191. scene = _this.getScene();
  33192. _this.name = name;
  33193. _this.isRenderTarget = true;
  33194. _this._size = size;
  33195. _this._generateMipMaps = generateMipMaps;
  33196. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  33197. // Rendering groups
  33198. _this._renderingManager = new BABYLON.RenderingManager(scene);
  33199. if (isMulti) {
  33200. return _this;
  33201. }
  33202. _this._renderTargetOptions = {
  33203. generateMipMaps: generateMipMaps,
  33204. type: type,
  33205. samplingMode: samplingMode,
  33206. generateDepthBuffer: generateDepthBuffer,
  33207. generateStencilBuffer: generateStencilBuffer
  33208. };
  33209. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  33210. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33211. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33212. }
  33213. if (isCube) {
  33214. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  33215. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  33216. _this._textureMatrix = BABYLON.Matrix.Identity();
  33217. }
  33218. else {
  33219. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  33220. }
  33221. return _this;
  33222. }
  33223. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  33224. get: function () {
  33225. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  33226. },
  33227. enumerable: true,
  33228. configurable: true
  33229. });
  33230. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  33231. get: function () {
  33232. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  33233. },
  33234. enumerable: true,
  33235. configurable: true
  33236. });
  33237. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  33238. get: function () {
  33239. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  33240. },
  33241. enumerable: true,
  33242. configurable: true
  33243. });
  33244. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  33245. set: function (callback) {
  33246. if (this._onAfterUnbindObserver) {
  33247. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  33248. }
  33249. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  33250. },
  33251. enumerable: true,
  33252. configurable: true
  33253. });
  33254. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  33255. set: function (callback) {
  33256. if (this._onBeforeRenderObserver) {
  33257. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  33258. }
  33259. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  33260. },
  33261. enumerable: true,
  33262. configurable: true
  33263. });
  33264. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  33265. set: function (callback) {
  33266. if (this._onAfterRenderObserver) {
  33267. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  33268. }
  33269. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  33270. },
  33271. enumerable: true,
  33272. configurable: true
  33273. });
  33274. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  33275. set: function (callback) {
  33276. if (this._onClearObserver) {
  33277. this.onClearObservable.remove(this._onClearObserver);
  33278. }
  33279. this._onClearObserver = this.onClearObservable.add(callback);
  33280. },
  33281. enumerable: true,
  33282. configurable: true
  33283. });
  33284. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  33285. get: function () {
  33286. return this._renderTargetOptions;
  33287. },
  33288. enumerable: true,
  33289. configurable: true
  33290. });
  33291. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  33292. get: function () {
  33293. return this._samples;
  33294. },
  33295. set: function (value) {
  33296. if (this._samples === value) {
  33297. return;
  33298. }
  33299. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  33300. },
  33301. enumerable: true,
  33302. configurable: true
  33303. });
  33304. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  33305. this._currentRefreshId = -1;
  33306. };
  33307. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  33308. get: function () {
  33309. return this._refreshRate;
  33310. },
  33311. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  33312. set: function (value) {
  33313. this._refreshRate = value;
  33314. this.resetRefreshCounter();
  33315. },
  33316. enumerable: true,
  33317. configurable: true
  33318. });
  33319. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  33320. if (!this._postProcessManager) {
  33321. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  33322. this._postProcesses = new Array();
  33323. }
  33324. this._postProcesses.push(postProcess);
  33325. this._postProcesses[0].autoClear = false;
  33326. };
  33327. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  33328. if (!this._postProcesses) {
  33329. return;
  33330. }
  33331. if (dispose) {
  33332. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  33333. var postProcess = _a[_i];
  33334. postProcess.dispose();
  33335. postProcess = null;
  33336. }
  33337. }
  33338. this._postProcesses = [];
  33339. };
  33340. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  33341. if (!this._postProcesses) {
  33342. return;
  33343. }
  33344. var index = this._postProcesses.indexOf(postProcess);
  33345. if (index === -1) {
  33346. return;
  33347. }
  33348. this._postProcesses.splice(index, 1);
  33349. if (this._postProcesses.length > 0) {
  33350. this._postProcesses[0].autoClear = false;
  33351. }
  33352. };
  33353. RenderTargetTexture.prototype._shouldRender = function () {
  33354. if (this._currentRefreshId === -1) {
  33355. this._currentRefreshId = 1;
  33356. return true;
  33357. }
  33358. if (this.refreshRate === this._currentRefreshId) {
  33359. this._currentRefreshId = 1;
  33360. return true;
  33361. }
  33362. this._currentRefreshId++;
  33363. return false;
  33364. };
  33365. RenderTargetTexture.prototype.getRenderSize = function () {
  33366. return this._size;
  33367. };
  33368. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  33369. get: function () {
  33370. return true;
  33371. },
  33372. enumerable: true,
  33373. configurable: true
  33374. });
  33375. RenderTargetTexture.prototype.scale = function (ratio) {
  33376. var newSize = this._size * ratio;
  33377. this.resize(newSize);
  33378. };
  33379. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  33380. if (this.isCube) {
  33381. return this._textureMatrix;
  33382. }
  33383. return _super.prototype.getReflectionTextureMatrix.call(this);
  33384. };
  33385. RenderTargetTexture.prototype.resize = function (size) {
  33386. this.releaseInternalTexture();
  33387. if (this.isCube) {
  33388. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  33389. }
  33390. else {
  33391. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  33392. }
  33393. };
  33394. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  33395. var scene = this.getScene();
  33396. var engine = scene.getEngine();
  33397. if (this.useCameraPostProcesses !== undefined) {
  33398. useCameraPostProcess = this.useCameraPostProcesses;
  33399. }
  33400. if (this._waitingRenderList) {
  33401. this.renderList = [];
  33402. for (var index = 0; index < this._waitingRenderList.length; index++) {
  33403. var id = this._waitingRenderList[index];
  33404. this.renderList.push(scene.getMeshByID(id));
  33405. }
  33406. delete this._waitingRenderList;
  33407. }
  33408. // Is predicate defined?
  33409. if (this.renderListPredicate) {
  33410. this.renderList.splice(0); // Clear previous renderList
  33411. var sceneMeshes = this.getScene().meshes;
  33412. for (var index = 0; index < sceneMeshes.length; index++) {
  33413. var mesh = sceneMeshes[index];
  33414. if (this.renderListPredicate(mesh)) {
  33415. this.renderList.push(mesh);
  33416. }
  33417. }
  33418. }
  33419. if (this.renderList && this.renderList.length === 0) {
  33420. return;
  33421. }
  33422. this.onBeforeBindObservable.notifyObservers(this);
  33423. // Set custom projection.
  33424. // Needs to be before binding to prevent changing the aspect ratio.
  33425. var camera;
  33426. if (this.activeCamera) {
  33427. camera = this.activeCamera;
  33428. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  33429. if (this.activeCamera !== scene.activeCamera) {
  33430. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  33431. }
  33432. }
  33433. else {
  33434. camera = scene.activeCamera;
  33435. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  33436. }
  33437. // Prepare renderingManager
  33438. this._renderingManager.reset();
  33439. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  33440. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  33441. var sceneRenderId = scene.getRenderId();
  33442. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  33443. var mesh = currentRenderList[meshIndex];
  33444. if (mesh) {
  33445. if (!mesh.isReady()) {
  33446. // Reset _currentRefreshId
  33447. this.resetRefreshCounter();
  33448. continue;
  33449. }
  33450. mesh._preActivateForIntermediateRendering(sceneRenderId);
  33451. var isMasked = void 0;
  33452. if (!this.renderList) {
  33453. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  33454. }
  33455. else {
  33456. isMasked = false;
  33457. }
  33458. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  33459. mesh._activate(sceneRenderId);
  33460. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33461. var subMesh = mesh.subMeshes[subIndex];
  33462. scene._activeIndices.addCount(subMesh.indexCount, false);
  33463. this._renderingManager.dispatch(subMesh);
  33464. }
  33465. }
  33466. }
  33467. }
  33468. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  33469. var particleSystem = scene.particleSystems[particleIndex];
  33470. var emitter = particleSystem.emitter;
  33471. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  33472. continue;
  33473. }
  33474. if (currentRenderList.indexOf(emitter) >= 0) {
  33475. this._renderingManager.dispatchParticles(particleSystem);
  33476. }
  33477. }
  33478. if (this.isCube) {
  33479. for (var face = 0; face < 6; face++) {
  33480. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  33481. scene.incrementRenderId();
  33482. scene.resetCachedMaterial();
  33483. }
  33484. }
  33485. else {
  33486. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  33487. }
  33488. this.onAfterUnbindObservable.notifyObservers(this);
  33489. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  33490. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  33491. }
  33492. engine.setViewport(scene.activeCamera.viewport);
  33493. scene.resetCachedMaterial();
  33494. };
  33495. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  33496. var _this = this;
  33497. var scene = this.getScene();
  33498. var engine = scene.getEngine();
  33499. // Bind
  33500. if (this._postProcessManager) {
  33501. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  33502. }
  33503. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  33504. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  33505. }
  33506. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  33507. // Clear
  33508. if (this.onClearObservable.hasObservers()) {
  33509. this.onClearObservable.notifyObservers(engine);
  33510. }
  33511. else {
  33512. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  33513. }
  33514. if (!this._doNotChangeAspectRatio) {
  33515. scene.updateTransformMatrix(true);
  33516. }
  33517. // Render
  33518. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  33519. if (this._postProcessManager) {
  33520. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  33521. }
  33522. else if (useCameraPostProcess) {
  33523. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  33524. }
  33525. if (!this._doNotChangeAspectRatio) {
  33526. scene.updateTransformMatrix(true);
  33527. }
  33528. // Dump ?
  33529. if (dumpForDebug) {
  33530. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  33531. }
  33532. // Unbind
  33533. if (!this.isCube || faceIndex === 5) {
  33534. if (this.isCube) {
  33535. if (faceIndex === 5) {
  33536. engine.generateMipMapsForCubemap(this._texture);
  33537. }
  33538. }
  33539. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  33540. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  33541. });
  33542. }
  33543. else {
  33544. this.onAfterRenderObservable.notifyObservers(faceIndex);
  33545. }
  33546. };
  33547. /**
  33548. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  33549. * This allowed control for front to back rendering or reversly depending of the special needs.
  33550. *
  33551. * @param renderingGroupId The rendering group id corresponding to its index
  33552. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  33553. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  33554. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  33555. */
  33556. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  33557. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  33558. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  33559. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  33560. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  33561. };
  33562. /**
  33563. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  33564. *
  33565. * @param renderingGroupId The rendering group id corresponding to its index
  33566. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  33567. */
  33568. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  33569. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  33570. };
  33571. RenderTargetTexture.prototype.clone = function () {
  33572. var textureSize = this.getSize();
  33573. 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);
  33574. // Base texture
  33575. newTexture.hasAlpha = this.hasAlpha;
  33576. newTexture.level = this.level;
  33577. // RenderTarget Texture
  33578. newTexture.coordinatesMode = this.coordinatesMode;
  33579. newTexture.renderList = this.renderList.slice(0);
  33580. return newTexture;
  33581. };
  33582. RenderTargetTexture.prototype.serialize = function () {
  33583. if (!this.name) {
  33584. return null;
  33585. }
  33586. var serializationObject = _super.prototype.serialize.call(this);
  33587. serializationObject.renderTargetSize = this.getRenderSize();
  33588. serializationObject.renderList = [];
  33589. for (var index = 0; index < this.renderList.length; index++) {
  33590. serializationObject.renderList.push(this.renderList[index].id);
  33591. }
  33592. return serializationObject;
  33593. };
  33594. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  33595. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  33596. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  33597. };
  33598. RenderTargetTexture.prototype.dispose = function () {
  33599. if (this._postProcessManager) {
  33600. this._postProcessManager.dispose();
  33601. this._postProcessManager = null;
  33602. }
  33603. this.clearPostProcesses(true);
  33604. this.renderList = null;
  33605. // Remove from custom render targets
  33606. var scene = this.getScene();
  33607. var index = scene.customRenderTargets.indexOf(this);
  33608. if (index >= 0) {
  33609. scene.customRenderTargets.splice(index, 1);
  33610. }
  33611. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  33612. var camera = _a[_i];
  33613. index = camera.customRenderTargets.indexOf(this);
  33614. if (index >= 0) {
  33615. camera.customRenderTargets.splice(index, 1);
  33616. }
  33617. }
  33618. _super.prototype.dispose.call(this);
  33619. };
  33620. RenderTargetTexture.prototype._rebuild = function () {
  33621. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  33622. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  33623. }
  33624. if (this._postProcessManager) {
  33625. this._postProcessManager._rebuild();
  33626. }
  33627. };
  33628. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  33629. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  33630. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  33631. return RenderTargetTexture;
  33632. }(BABYLON.Texture));
  33633. BABYLON.RenderTargetTexture = RenderTargetTexture;
  33634. })(BABYLON || (BABYLON = {}));
  33635. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  33636. var BABYLON;
  33637. (function (BABYLON) {
  33638. ;
  33639. var MultiRenderTarget = (function (_super) {
  33640. __extends(MultiRenderTarget, _super);
  33641. function MultiRenderTarget(name, size, count, scene, options) {
  33642. var _this = this;
  33643. options = options || {};
  33644. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  33645. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  33646. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  33647. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  33648. if (!_this.isSupported) {
  33649. _this.dispose();
  33650. return;
  33651. }
  33652. var types = [];
  33653. var samplingModes = [];
  33654. for (var i = 0; i < count; i++) {
  33655. if (options.types && options.types[i]) {
  33656. types.push(options.types[i]);
  33657. }
  33658. else {
  33659. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  33660. }
  33661. if (options.samplingModes && options.samplingModes[i]) {
  33662. samplingModes.push(options.samplingModes[i]);
  33663. }
  33664. else {
  33665. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33666. }
  33667. }
  33668. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  33669. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  33670. _this._count = count;
  33671. _this._size = size;
  33672. _this._multiRenderTargetOptions = {
  33673. samplingModes: samplingModes,
  33674. generateMipMaps: generateMipMaps,
  33675. generateDepthBuffer: generateDepthBuffer,
  33676. generateStencilBuffer: generateStencilBuffer,
  33677. generateDepthTexture: generateDepthTexture,
  33678. types: types,
  33679. textureCount: count
  33680. };
  33681. _this._createInternalTextures();
  33682. _this._createTextures();
  33683. return _this;
  33684. }
  33685. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  33686. get: function () {
  33687. var engine = this.getScene().getEngine();
  33688. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  33689. },
  33690. enumerable: true,
  33691. configurable: true
  33692. });
  33693. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  33694. get: function () {
  33695. return this._textures;
  33696. },
  33697. enumerable: true,
  33698. configurable: true
  33699. });
  33700. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  33701. get: function () {
  33702. return this._textures[this._textures.length - 1];
  33703. },
  33704. enumerable: true,
  33705. configurable: true
  33706. });
  33707. MultiRenderTarget.prototype._rebuild = function () {
  33708. this.releaseInternalTextures();
  33709. this._createInternalTextures();
  33710. for (var i = 0; i < this._internalTextures.length; i++) {
  33711. var texture = this._textures[i];
  33712. texture._texture = this._internalTextures[i];
  33713. }
  33714. // Keeps references to frame buffer and stencil/depth buffer
  33715. this._texture = this._internalTextures[0];
  33716. };
  33717. MultiRenderTarget.prototype._createInternalTextures = function () {
  33718. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  33719. };
  33720. MultiRenderTarget.prototype._createTextures = function () {
  33721. this._textures = [];
  33722. for (var i = 0; i < this._internalTextures.length; i++) {
  33723. var texture = new BABYLON.Texture(null, this.getScene());
  33724. texture._texture = this._internalTextures[i];
  33725. this._textures.push(texture);
  33726. }
  33727. // Keeps references to frame buffer and stencil/depth buffer
  33728. this._texture = this._internalTextures[0];
  33729. };
  33730. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  33731. get: function () {
  33732. return this._samples;
  33733. },
  33734. set: function (value) {
  33735. if (this._samples === value) {
  33736. return;
  33737. }
  33738. for (var i = 0; i < this._internalTextures.length; i++) {
  33739. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  33740. }
  33741. },
  33742. enumerable: true,
  33743. configurable: true
  33744. });
  33745. MultiRenderTarget.prototype.resize = function (size) {
  33746. this.releaseInternalTextures();
  33747. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  33748. this._createInternalTextures();
  33749. };
  33750. MultiRenderTarget.prototype.dispose = function () {
  33751. this.releaseInternalTextures();
  33752. _super.prototype.dispose.call(this);
  33753. };
  33754. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  33755. if (!this._internalTextures) {
  33756. return;
  33757. }
  33758. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  33759. if (this._internalTextures[i] !== undefined) {
  33760. this._internalTextures[i].dispose();
  33761. this._internalTextures.splice(i, 1);
  33762. }
  33763. }
  33764. };
  33765. return MultiRenderTarget;
  33766. }(BABYLON.RenderTargetTexture));
  33767. BABYLON.MultiRenderTarget = MultiRenderTarget;
  33768. })(BABYLON || (BABYLON = {}));
  33769. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  33770. /// <reference path="babylon.renderTargetTexture.ts" />
  33771. var BABYLON;
  33772. (function (BABYLON) {
  33773. var MirrorTexture = (function (_super) {
  33774. __extends(MirrorTexture, _super);
  33775. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  33776. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33777. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33778. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  33779. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  33780. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  33781. _this._transformMatrix = BABYLON.Matrix.Zero();
  33782. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  33783. _this._blurKernelX = 0;
  33784. _this._blurKernelY = 0;
  33785. _this._blurRatio = 1.0;
  33786. _this.onBeforeRenderObservable.add(function () {
  33787. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  33788. _this._savedViewMatrix = scene.getViewMatrix();
  33789. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  33790. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  33791. scene.clipPlane = _this.mirrorPlane;
  33792. scene.getEngine().cullBackFaces = false;
  33793. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  33794. });
  33795. _this.onAfterRenderObservable.add(function () {
  33796. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  33797. scene.getEngine().cullBackFaces = true;
  33798. scene._mirroredCameraPosition = null;
  33799. delete scene.clipPlane;
  33800. });
  33801. return _this;
  33802. }
  33803. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  33804. get: function () {
  33805. return this._blurRatio;
  33806. },
  33807. set: function (value) {
  33808. if (this._blurRatio === value) {
  33809. return;
  33810. }
  33811. this._blurRatio = value;
  33812. this._preparePostProcesses();
  33813. },
  33814. enumerable: true,
  33815. configurable: true
  33816. });
  33817. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  33818. set: function (value) {
  33819. this.blurKernelX = value;
  33820. this.blurKernelY = value;
  33821. },
  33822. enumerable: true,
  33823. configurable: true
  33824. });
  33825. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  33826. get: function () {
  33827. return this._blurKernelX;
  33828. },
  33829. set: function (value) {
  33830. if (this._blurKernelX === value) {
  33831. return;
  33832. }
  33833. this._blurKernelX = value;
  33834. this._preparePostProcesses();
  33835. },
  33836. enumerable: true,
  33837. configurable: true
  33838. });
  33839. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  33840. get: function () {
  33841. return this._blurKernelY;
  33842. },
  33843. set: function (value) {
  33844. if (this._blurKernelY === value) {
  33845. return;
  33846. }
  33847. this._blurKernelY = value;
  33848. this._preparePostProcesses();
  33849. },
  33850. enumerable: true,
  33851. configurable: true
  33852. });
  33853. MirrorTexture.prototype._preparePostProcesses = function () {
  33854. this.clearPostProcesses(true);
  33855. if (this._blurKernelX && this._blurKernelY) {
  33856. var engine = this.getScene().getEngine();
  33857. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33858. 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);
  33859. this._blurX.autoClear = false;
  33860. if (this._blurRatio === 1 && this.samples < 2) {
  33861. this._blurX.outputTexture = this._texture;
  33862. }
  33863. else {
  33864. this._blurX.alwaysForcePOT = true;
  33865. }
  33866. 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);
  33867. this._blurY.autoClear = false;
  33868. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  33869. this.addPostProcess(this._blurX);
  33870. this.addPostProcess(this._blurY);
  33871. }
  33872. };
  33873. MirrorTexture.prototype.clone = function () {
  33874. var textureSize = this.getSize();
  33875. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  33876. // Base texture
  33877. newTexture.hasAlpha = this.hasAlpha;
  33878. newTexture.level = this.level;
  33879. // Mirror Texture
  33880. newTexture.mirrorPlane = this.mirrorPlane.clone();
  33881. newTexture.renderList = this.renderList.slice(0);
  33882. return newTexture;
  33883. };
  33884. MirrorTexture.prototype.serialize = function () {
  33885. if (!this.name) {
  33886. return null;
  33887. }
  33888. var serializationObject = _super.prototype.serialize.call(this);
  33889. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  33890. return serializationObject;
  33891. };
  33892. return MirrorTexture;
  33893. }(BABYLON.RenderTargetTexture));
  33894. BABYLON.MirrorTexture = MirrorTexture;
  33895. })(BABYLON || (BABYLON = {}));
  33896. //# sourceMappingURL=babylon.mirrorTexture.js.map
  33897. /// <reference path="babylon.renderTargetTexture.ts" />
  33898. var BABYLON;
  33899. (function (BABYLON) {
  33900. /**
  33901. * Creates a refraction texture used by refraction channel of the standard material.
  33902. * @param name the texture name
  33903. * @param size size of the underlying texture
  33904. * @param scene root scene
  33905. */
  33906. var RefractionTexture = (function (_super) {
  33907. __extends(RefractionTexture, _super);
  33908. function RefractionTexture(name, size, scene, generateMipMaps) {
  33909. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  33910. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  33911. _this.depth = 2.0;
  33912. _this.onBeforeRenderObservable.add(function () {
  33913. scene.clipPlane = _this.refractionPlane;
  33914. });
  33915. _this.onAfterRenderObservable.add(function () {
  33916. delete scene.clipPlane;
  33917. });
  33918. return _this;
  33919. }
  33920. RefractionTexture.prototype.clone = function () {
  33921. var textureSize = this.getSize();
  33922. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  33923. // Base texture
  33924. newTexture.hasAlpha = this.hasAlpha;
  33925. newTexture.level = this.level;
  33926. // Refraction Texture
  33927. newTexture.refractionPlane = this.refractionPlane.clone();
  33928. newTexture.renderList = this.renderList.slice(0);
  33929. newTexture.depth = this.depth;
  33930. return newTexture;
  33931. };
  33932. RefractionTexture.prototype.serialize = function () {
  33933. if (!this.name) {
  33934. return null;
  33935. }
  33936. var serializationObject = _super.prototype.serialize.call(this);
  33937. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  33938. serializationObject.depth = this.depth;
  33939. return serializationObject;
  33940. };
  33941. return RefractionTexture;
  33942. }(BABYLON.RenderTargetTexture));
  33943. BABYLON.RefractionTexture = RefractionTexture;
  33944. })(BABYLON || (BABYLON = {}));
  33945. //# sourceMappingURL=babylon.refractionTexture.js.map
  33946. /// <reference path="babylon.texture.ts" />
  33947. var BABYLON;
  33948. (function (BABYLON) {
  33949. var DynamicTexture = (function (_super) {
  33950. __extends(DynamicTexture, _super);
  33951. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  33952. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33953. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  33954. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  33955. _this.name = name;
  33956. var engine = _this.getScene().getEngine();
  33957. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33958. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33959. _this._generateMipMaps = generateMipMaps;
  33960. if (options.getContext) {
  33961. _this._canvas = options;
  33962. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33963. }
  33964. else {
  33965. _this._canvas = document.createElement("canvas");
  33966. if (options.width) {
  33967. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33968. }
  33969. else {
  33970. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  33971. }
  33972. }
  33973. var textureSize = _this.getSize();
  33974. _this._canvas.width = textureSize.width;
  33975. _this._canvas.height = textureSize.height;
  33976. _this._context = _this._canvas.getContext("2d");
  33977. return _this;
  33978. }
  33979. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  33980. get: function () {
  33981. return true;
  33982. },
  33983. enumerable: true,
  33984. configurable: true
  33985. });
  33986. DynamicTexture.prototype._recreate = function (textureSize) {
  33987. this._canvas.width = textureSize.width;
  33988. this._canvas.height = textureSize.height;
  33989. this.releaseInternalTexture();
  33990. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  33991. };
  33992. DynamicTexture.prototype.scale = function (ratio) {
  33993. var textureSize = this.getSize();
  33994. textureSize.width *= ratio;
  33995. textureSize.height *= ratio;
  33996. this._recreate(textureSize);
  33997. };
  33998. DynamicTexture.prototype.scaleTo = function (width, height) {
  33999. var textureSize = this.getSize();
  34000. textureSize.width = width;
  34001. textureSize.height = height;
  34002. this._recreate(textureSize);
  34003. };
  34004. DynamicTexture.prototype.getContext = function () {
  34005. return this._context;
  34006. };
  34007. DynamicTexture.prototype.clear = function () {
  34008. var size = this.getSize();
  34009. this._context.fillRect(0, 0, size.width, size.height);
  34010. };
  34011. DynamicTexture.prototype.update = function (invertY) {
  34012. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  34013. };
  34014. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  34015. if (update === void 0) { update = true; }
  34016. var size = this.getSize();
  34017. if (clearColor) {
  34018. this._context.fillStyle = clearColor;
  34019. this._context.fillRect(0, 0, size.width, size.height);
  34020. }
  34021. this._context.font = font;
  34022. if (x === null || x === undefined) {
  34023. var textSize = this._context.measureText(text);
  34024. x = (size.width - textSize.width) / 2;
  34025. }
  34026. if (y === null || y === undefined) {
  34027. var fontSize = parseInt((font.replace(/\D/g, '')));
  34028. ;
  34029. y = (size.height / 2) + (fontSize / 3.65);
  34030. }
  34031. this._context.fillStyle = color;
  34032. this._context.fillText(text, x, y);
  34033. if (update) {
  34034. this.update(invertY);
  34035. }
  34036. };
  34037. DynamicTexture.prototype.clone = function () {
  34038. var textureSize = this.getSize();
  34039. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  34040. // Base texture
  34041. newTexture.hasAlpha = this.hasAlpha;
  34042. newTexture.level = this.level;
  34043. // Dynamic Texture
  34044. newTexture.wrapU = this.wrapU;
  34045. newTexture.wrapV = this.wrapV;
  34046. return newTexture;
  34047. };
  34048. DynamicTexture.prototype._rebuild = function () {
  34049. this.update();
  34050. };
  34051. return DynamicTexture;
  34052. }(BABYLON.Texture));
  34053. BABYLON.DynamicTexture = DynamicTexture;
  34054. })(BABYLON || (BABYLON = {}));
  34055. //# sourceMappingURL=babylon.dynamicTexture.js.map
  34056. var BABYLON;
  34057. (function (BABYLON) {
  34058. var VideoTexture = (function (_super) {
  34059. __extends(VideoTexture, _super);
  34060. /**
  34061. * Creates a video texture.
  34062. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  34063. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  34064. * @param {BABYLON.Scene} scene is obviously the current scene.
  34065. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  34066. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  34067. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  34068. */
  34069. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  34070. if (generateMipMaps === void 0) { generateMipMaps = false; }
  34071. if (invertY === void 0) { invertY = false; }
  34072. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34073. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  34074. _this._autoLaunch = true;
  34075. var urls;
  34076. _this.name = name;
  34077. if (urlsOrVideo instanceof HTMLVideoElement) {
  34078. _this.video = urlsOrVideo;
  34079. }
  34080. else {
  34081. urls = urlsOrVideo;
  34082. _this.video = document.createElement("video");
  34083. _this.video.autoplay = false;
  34084. _this.video.loop = true;
  34085. }
  34086. _this._generateMipMaps = generateMipMaps;
  34087. _this._samplingMode = samplingMode;
  34088. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  34089. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34090. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34091. }
  34092. else {
  34093. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34094. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34095. _this._generateMipMaps = false;
  34096. }
  34097. if (urls) {
  34098. _this.video.addEventListener("canplay", function () {
  34099. _this._createTexture();
  34100. });
  34101. urls.forEach(function (url) {
  34102. var source = document.createElement("source");
  34103. source.src = url;
  34104. _this.video.appendChild(source);
  34105. });
  34106. }
  34107. else {
  34108. _this._createTexture();
  34109. }
  34110. _this._lastUpdate = BABYLON.Tools.Now;
  34111. return _this;
  34112. }
  34113. VideoTexture.prototype.__setTextureReady = function () {
  34114. this._texture.isReady = true;
  34115. };
  34116. VideoTexture.prototype._createTexture = function () {
  34117. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  34118. if (this._autoLaunch) {
  34119. this._autoLaunch = false;
  34120. this.video.play();
  34121. }
  34122. this._setTextureReady = this.__setTextureReady.bind(this);
  34123. this.video.addEventListener("playing", this._setTextureReady);
  34124. };
  34125. VideoTexture.prototype._rebuild = function () {
  34126. this.update();
  34127. };
  34128. VideoTexture.prototype.update = function () {
  34129. var now = BABYLON.Tools.Now;
  34130. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  34131. return false;
  34132. }
  34133. this._lastUpdate = now;
  34134. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  34135. return true;
  34136. };
  34137. VideoTexture.prototype.dispose = function () {
  34138. _super.prototype.dispose.call(this);
  34139. this.video.removeEventListener("playing", this._setTextureReady);
  34140. };
  34141. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  34142. var video = document.createElement("video");
  34143. var constraintsDeviceId;
  34144. if (constraints && constraints.deviceId) {
  34145. constraintsDeviceId = {
  34146. exact: constraints.deviceId
  34147. };
  34148. }
  34149. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  34150. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  34151. if (navigator.getUserMedia) {
  34152. navigator.getUserMedia({
  34153. video: {
  34154. deviceId: constraintsDeviceId,
  34155. width: {
  34156. min: (constraints && constraints.minWidth) || 256,
  34157. max: (constraints && constraints.maxWidth) || 640
  34158. },
  34159. height: {
  34160. min: (constraints && constraints.minHeight) || 256,
  34161. max: (constraints && constraints.maxHeight) || 480
  34162. }
  34163. }
  34164. }, function (stream) {
  34165. if (video.mozSrcObject !== undefined) {
  34166. video.mozSrcObject = stream;
  34167. }
  34168. else {
  34169. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  34170. }
  34171. video.play();
  34172. if (onReady) {
  34173. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  34174. }
  34175. }, function (e) {
  34176. BABYLON.Tools.Error(e.name);
  34177. });
  34178. }
  34179. };
  34180. return VideoTexture;
  34181. }(BABYLON.Texture));
  34182. BABYLON.VideoTexture = VideoTexture;
  34183. })(BABYLON || (BABYLON = {}));
  34184. //# sourceMappingURL=babylon.videoTexture.js.map
  34185. var BABYLON;
  34186. (function (BABYLON) {
  34187. var RawTexture = (function (_super) {
  34188. __extends(RawTexture, _super);
  34189. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  34190. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34191. if (invertY === void 0) { invertY = false; }
  34192. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34193. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  34194. _this.format = format;
  34195. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  34196. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34197. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34198. return _this;
  34199. }
  34200. RawTexture.prototype.update = function (data) {
  34201. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  34202. };
  34203. // Statics
  34204. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34205. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34206. if (invertY === void 0) { invertY = false; }
  34207. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34208. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  34209. };
  34210. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34211. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34212. if (invertY === void 0) { invertY = false; }
  34213. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34214. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34215. };
  34216. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34217. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34218. if (invertY === void 0) { invertY = false; }
  34219. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34220. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34221. };
  34222. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34223. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34224. if (invertY === void 0) { invertY = false; }
  34225. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34226. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  34227. };
  34228. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34229. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34230. if (invertY === void 0) { invertY = false; }
  34231. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34232. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  34233. };
  34234. return RawTexture;
  34235. }(BABYLON.Texture));
  34236. BABYLON.RawTexture = RawTexture;
  34237. })(BABYLON || (BABYLON = {}));
  34238. //# sourceMappingURL=babylon.rawTexture.js.map
  34239. var BABYLON;
  34240. (function (BABYLON) {
  34241. var Internals;
  34242. (function (Internals) {
  34243. /*
  34244. * Based on jsTGALoader - Javascript loader for TGA file
  34245. * By Vincent Thibault
  34246. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  34247. */
  34248. var TGATools = (function () {
  34249. function TGATools() {
  34250. }
  34251. TGATools.GetTGAHeader = function (data) {
  34252. var offset = 0;
  34253. var header = {
  34254. id_length: data[offset++],
  34255. colormap_type: data[offset++],
  34256. image_type: data[offset++],
  34257. colormap_index: data[offset++] | data[offset++] << 8,
  34258. colormap_length: data[offset++] | data[offset++] << 8,
  34259. colormap_size: data[offset++],
  34260. origin: [
  34261. data[offset++] | data[offset++] << 8,
  34262. data[offset++] | data[offset++] << 8
  34263. ],
  34264. width: data[offset++] | data[offset++] << 8,
  34265. height: data[offset++] | data[offset++] << 8,
  34266. pixel_size: data[offset++],
  34267. flags: data[offset++]
  34268. };
  34269. return header;
  34270. };
  34271. TGATools.UploadContent = function (gl, data) {
  34272. // Not enough data to contain header ?
  34273. if (data.length < 19) {
  34274. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  34275. return;
  34276. }
  34277. // Read Header
  34278. var offset = 18;
  34279. var header = TGATools.GetTGAHeader(data);
  34280. // Assume it's a valid Targa file.
  34281. if (header.id_length + offset > data.length) {
  34282. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  34283. return;
  34284. }
  34285. // Skip not needed data
  34286. offset += header.id_length;
  34287. var use_rle = false;
  34288. var use_pal = false;
  34289. var use_rgb = false;
  34290. var use_grey = false;
  34291. // Get some informations.
  34292. switch (header.image_type) {
  34293. case TGATools._TYPE_RLE_INDEXED:
  34294. use_rle = true;
  34295. case TGATools._TYPE_INDEXED:
  34296. use_pal = true;
  34297. break;
  34298. case TGATools._TYPE_RLE_RGB:
  34299. use_rle = true;
  34300. case TGATools._TYPE_RGB:
  34301. use_rgb = true;
  34302. break;
  34303. case TGATools._TYPE_RLE_GREY:
  34304. use_rle = true;
  34305. case TGATools._TYPE_GREY:
  34306. use_grey = true;
  34307. break;
  34308. }
  34309. var pixel_data;
  34310. var numAlphaBits = header.flags & 0xf;
  34311. var pixel_size = header.pixel_size >> 3;
  34312. var pixel_total = header.width * header.height * pixel_size;
  34313. // Read palettes
  34314. var palettes;
  34315. if (use_pal) {
  34316. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  34317. }
  34318. // Read LRE
  34319. if (use_rle) {
  34320. pixel_data = new Uint8Array(pixel_total);
  34321. var c, count, i;
  34322. var localOffset = 0;
  34323. var pixels = new Uint8Array(pixel_size);
  34324. while (offset < pixel_total && localOffset < pixel_total) {
  34325. c = data[offset++];
  34326. count = (c & 0x7f) + 1;
  34327. // RLE pixels
  34328. if (c & 0x80) {
  34329. // Bind pixel tmp array
  34330. for (i = 0; i < pixel_size; ++i) {
  34331. pixels[i] = data[offset++];
  34332. }
  34333. // Copy pixel array
  34334. for (i = 0; i < count; ++i) {
  34335. pixel_data.set(pixels, localOffset + i * pixel_size);
  34336. }
  34337. localOffset += pixel_size * count;
  34338. }
  34339. else {
  34340. count *= pixel_size;
  34341. for (i = 0; i < count; ++i) {
  34342. pixel_data[localOffset + i] = data[offset++];
  34343. }
  34344. localOffset += count;
  34345. }
  34346. }
  34347. }
  34348. else {
  34349. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  34350. }
  34351. // Load to texture
  34352. var x_start, y_start, x_step, y_step, y_end, x_end;
  34353. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  34354. default:
  34355. case TGATools._ORIGIN_UL:
  34356. x_start = 0;
  34357. x_step = 1;
  34358. x_end = header.width;
  34359. y_start = 0;
  34360. y_step = 1;
  34361. y_end = header.height;
  34362. break;
  34363. case TGATools._ORIGIN_BL:
  34364. x_start = 0;
  34365. x_step = 1;
  34366. x_end = header.width;
  34367. y_start = header.height - 1;
  34368. y_step = -1;
  34369. y_end = -1;
  34370. break;
  34371. case TGATools._ORIGIN_UR:
  34372. x_start = header.width - 1;
  34373. x_step = -1;
  34374. x_end = -1;
  34375. y_start = 0;
  34376. y_step = 1;
  34377. y_end = header.height;
  34378. break;
  34379. case TGATools._ORIGIN_BR:
  34380. x_start = header.width - 1;
  34381. x_step = -1;
  34382. x_end = -1;
  34383. y_start = header.height - 1;
  34384. y_step = -1;
  34385. y_end = -1;
  34386. break;
  34387. }
  34388. // Load the specify method
  34389. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  34390. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  34391. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  34392. };
  34393. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34394. var image = pixel_data, colormap = palettes;
  34395. var width = header.width, height = header.height;
  34396. var color, i = 0, x, y;
  34397. var imageData = new Uint8Array(width * height * 4);
  34398. for (y = y_start; y !== y_end; y += y_step) {
  34399. for (x = x_start; x !== x_end; x += x_step, i++) {
  34400. color = image[i];
  34401. imageData[(x + width * y) * 4 + 3] = 255;
  34402. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  34403. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  34404. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  34405. }
  34406. }
  34407. return imageData;
  34408. };
  34409. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34410. var image = pixel_data;
  34411. var width = header.width, height = header.height;
  34412. var color, i = 0, x, y;
  34413. var imageData = new Uint8Array(width * height * 4);
  34414. for (y = y_start; y !== y_end; y += y_step) {
  34415. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  34416. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  34417. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  34418. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  34419. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  34420. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  34421. }
  34422. }
  34423. return imageData;
  34424. };
  34425. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34426. var image = pixel_data;
  34427. var width = header.width, height = header.height;
  34428. var i = 0, x, y;
  34429. var imageData = new Uint8Array(width * height * 4);
  34430. for (y = y_start; y !== y_end; y += y_step) {
  34431. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  34432. imageData[(x + width * y) * 4 + 3] = 255;
  34433. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34434. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  34435. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  34436. }
  34437. }
  34438. return imageData;
  34439. };
  34440. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34441. var image = pixel_data;
  34442. var width = header.width, height = header.height;
  34443. var i = 0, x, y;
  34444. var imageData = new Uint8Array(width * height * 4);
  34445. for (y = y_start; y !== y_end; y += y_step) {
  34446. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  34447. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34448. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  34449. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  34450. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  34451. }
  34452. }
  34453. return imageData;
  34454. };
  34455. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34456. var image = pixel_data;
  34457. var width = header.width, height = header.height;
  34458. var color, i = 0, x, y;
  34459. var imageData = new Uint8Array(width * height * 4);
  34460. for (y = y_start; y !== y_end; y += y_step) {
  34461. for (x = x_start; x !== x_end; x += x_step, i++) {
  34462. color = image[i];
  34463. imageData[(x + width * y) * 4 + 0] = color;
  34464. imageData[(x + width * y) * 4 + 1] = color;
  34465. imageData[(x + width * y) * 4 + 2] = color;
  34466. imageData[(x + width * y) * 4 + 3] = 255;
  34467. }
  34468. }
  34469. return imageData;
  34470. };
  34471. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34472. var image = pixel_data;
  34473. var width = header.width, height = header.height;
  34474. var i = 0, x, y;
  34475. var imageData = new Uint8Array(width * height * 4);
  34476. for (y = y_start; y !== y_end; y += y_step) {
  34477. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  34478. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  34479. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  34480. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34481. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  34482. }
  34483. }
  34484. return imageData;
  34485. };
  34486. TGATools._TYPE_NO_DATA = 0;
  34487. TGATools._TYPE_INDEXED = 1;
  34488. TGATools._TYPE_RGB = 2;
  34489. TGATools._TYPE_GREY = 3;
  34490. TGATools._TYPE_RLE_INDEXED = 9;
  34491. TGATools._TYPE_RLE_RGB = 10;
  34492. TGATools._TYPE_RLE_GREY = 11;
  34493. TGATools._ORIGIN_MASK = 0x30;
  34494. TGATools._ORIGIN_SHIFT = 0x04;
  34495. TGATools._ORIGIN_BL = 0x00;
  34496. TGATools._ORIGIN_BR = 0x01;
  34497. TGATools._ORIGIN_UL = 0x02;
  34498. TGATools._ORIGIN_UR = 0x03;
  34499. return TGATools;
  34500. }());
  34501. Internals.TGATools = TGATools;
  34502. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34503. })(BABYLON || (BABYLON = {}));
  34504. //# sourceMappingURL=babylon.tga.js.map
  34505. var BABYLON;
  34506. (function (BABYLON) {
  34507. var Internals;
  34508. (function (Internals) {
  34509. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  34510. // All values and structures referenced from:
  34511. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  34512. var DDS_MAGIC = 0x20534444;
  34513. 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;
  34514. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  34515. 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;
  34516. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  34517. function FourCCToInt32(value) {
  34518. return value.charCodeAt(0) +
  34519. (value.charCodeAt(1) << 8) +
  34520. (value.charCodeAt(2) << 16) +
  34521. (value.charCodeAt(3) << 24);
  34522. }
  34523. function Int32ToFourCC(value) {
  34524. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  34525. }
  34526. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  34527. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  34528. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  34529. var FOURCC_DX10 = FourCCToInt32("DX10");
  34530. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  34531. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  34532. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  34533. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  34534. var headerLengthInt = 31; // The header length in 32 bit ints
  34535. // Offsets into the header array
  34536. var off_magic = 0;
  34537. var off_size = 1;
  34538. var off_flags = 2;
  34539. var off_height = 3;
  34540. var off_width = 4;
  34541. var off_mipmapCount = 7;
  34542. var off_pfFlags = 20;
  34543. var off_pfFourCC = 21;
  34544. var off_RGBbpp = 22;
  34545. var off_RMask = 23;
  34546. var off_GMask = 24;
  34547. var off_BMask = 25;
  34548. var off_AMask = 26;
  34549. var off_caps1 = 27;
  34550. var off_caps2 = 28;
  34551. var off_caps3 = 29;
  34552. var off_caps4 = 30;
  34553. var off_dxgiFormat = 32;
  34554. ;
  34555. var DDSTools = (function () {
  34556. function DDSTools() {
  34557. }
  34558. DDSTools.GetDDSInfo = function (arrayBuffer) {
  34559. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  34560. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  34561. var mipmapCount = 1;
  34562. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  34563. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34564. }
  34565. var fourCC = header[off_pfFourCC];
  34566. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  34567. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34568. switch (fourCC) {
  34569. case FOURCC_D3DFMT_R16G16B16A16F:
  34570. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  34571. break;
  34572. case FOURCC_D3DFMT_R32G32B32A32F:
  34573. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34574. break;
  34575. case FOURCC_DX10:
  34576. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  34577. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  34578. break;
  34579. }
  34580. }
  34581. return {
  34582. width: header[off_width],
  34583. height: header[off_height],
  34584. mipmapCount: mipmapCount,
  34585. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  34586. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  34587. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  34588. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  34589. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  34590. dxgiFormat: dxgiFormat,
  34591. textureType: textureType
  34592. };
  34593. };
  34594. DDSTools._ToHalfFloat = function (value) {
  34595. if (!DDSTools._FloatView) {
  34596. DDSTools._FloatView = new Float32Array(1);
  34597. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  34598. }
  34599. DDSTools._FloatView[0] = value;
  34600. var x = DDSTools._Int32View[0];
  34601. var bits = (x >> 16) & 0x8000; /* Get the sign */
  34602. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  34603. var e = (x >> 23) & 0xff; /* Using int is faster here */
  34604. /* If zero, or denormal, or exponent underflows too much for a denormal
  34605. * half, return signed zero. */
  34606. if (e < 103) {
  34607. return bits;
  34608. }
  34609. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  34610. if (e > 142) {
  34611. bits |= 0x7c00;
  34612. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  34613. * not Inf, so make sure we set one mantissa bit too. */
  34614. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  34615. return bits;
  34616. }
  34617. /* If exponent underflows but not too much, return a denormal */
  34618. if (e < 113) {
  34619. m |= 0x0800;
  34620. /* Extra rounding may overflow and set mantissa to 0 and exponent
  34621. * to 1, which is OK. */
  34622. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  34623. return bits;
  34624. }
  34625. bits |= ((e - 112) << 10) | (m >> 1);
  34626. bits += m & 1;
  34627. return bits;
  34628. };
  34629. DDSTools._FromHalfFloat = function (value) {
  34630. var s = (value & 0x8000) >> 15;
  34631. var e = (value & 0x7C00) >> 10;
  34632. var f = value & 0x03FF;
  34633. if (e === 0) {
  34634. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  34635. }
  34636. else if (e == 0x1F) {
  34637. return f ? NaN : ((s ? -1 : 1) * Infinity);
  34638. }
  34639. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  34640. };
  34641. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34642. var destArray = new Float32Array(dataLength);
  34643. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34644. var index = 0;
  34645. for (var y = 0; y < height; y++) {
  34646. for (var x = 0; x < width; x++) {
  34647. var srcPos = (x + y * width) * 4;
  34648. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  34649. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  34650. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  34651. if (DDSTools.StoreLODInAlphaChannel) {
  34652. destArray[index + 3] = lod;
  34653. }
  34654. else {
  34655. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  34656. }
  34657. index += 4;
  34658. }
  34659. }
  34660. return destArray;
  34661. };
  34662. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34663. if (DDSTools.StoreLODInAlphaChannel) {
  34664. var destArray = new Uint16Array(dataLength);
  34665. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34666. var index = 0;
  34667. for (var y = 0; y < height; y++) {
  34668. for (var x = 0; x < width; x++) {
  34669. var srcPos = (x + y * width) * 4;
  34670. destArray[index] = srcData[srcPos];
  34671. destArray[index + 1] = srcData[srcPos + 1];
  34672. destArray[index + 2] = srcData[srcPos + 2];
  34673. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  34674. index += 4;
  34675. }
  34676. }
  34677. return destArray;
  34678. }
  34679. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  34680. };
  34681. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34682. if (DDSTools.StoreLODInAlphaChannel) {
  34683. var destArray = new Float32Array(dataLength);
  34684. var srcData = new Float32Array(arrayBuffer, dataOffset);
  34685. var index = 0;
  34686. for (var y = 0; y < height; y++) {
  34687. for (var x = 0; x < width; x++) {
  34688. var srcPos = (x + y * width) * 4;
  34689. destArray[index] = srcData[srcPos];
  34690. destArray[index + 1] = srcData[srcPos + 1];
  34691. destArray[index + 2] = srcData[srcPos + 2];
  34692. destArray[index + 3] = lod;
  34693. index += 4;
  34694. }
  34695. }
  34696. return destArray;
  34697. }
  34698. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  34699. };
  34700. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34701. var destArray = new Uint8Array(dataLength);
  34702. var srcData = new Float32Array(arrayBuffer, dataOffset);
  34703. var index = 0;
  34704. for (var y = 0; y < height; y++) {
  34705. for (var x = 0; x < width; x++) {
  34706. var srcPos = (x + y * width) * 4;
  34707. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  34708. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  34709. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  34710. if (DDSTools.StoreLODInAlphaChannel) {
  34711. destArray[index + 3] = lod;
  34712. }
  34713. else {
  34714. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  34715. }
  34716. index += 4;
  34717. }
  34718. }
  34719. return destArray;
  34720. };
  34721. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34722. var destArray = new Uint8Array(dataLength);
  34723. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34724. var index = 0;
  34725. for (var y = 0; y < height; y++) {
  34726. for (var x = 0; x < width; x++) {
  34727. var srcPos = (x + y * width) * 4;
  34728. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  34729. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  34730. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  34731. if (DDSTools.StoreLODInAlphaChannel) {
  34732. destArray[index + 3] = lod;
  34733. }
  34734. else {
  34735. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  34736. }
  34737. index += 4;
  34738. }
  34739. }
  34740. return destArray;
  34741. };
  34742. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34743. var byteArray = new Uint8Array(dataLength);
  34744. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34745. var index = 0;
  34746. for (var y = 0; y < height; y++) {
  34747. for (var x = 0; x < width; x++) {
  34748. var srcPos = (x + y * width) * 4;
  34749. byteArray[index] = srcData[srcPos + 2];
  34750. byteArray[index + 1] = srcData[srcPos + 1];
  34751. byteArray[index + 2] = srcData[srcPos];
  34752. byteArray[index + 3] = srcData[srcPos + 3];
  34753. index += 4;
  34754. }
  34755. }
  34756. return byteArray;
  34757. };
  34758. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34759. var byteArray = new Uint8Array(dataLength);
  34760. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34761. var index = 0;
  34762. for (var y = 0; y < height; y++) {
  34763. for (var x = 0; x < width; x++) {
  34764. var srcPos = (x + y * width) * 3;
  34765. byteArray[index] = srcData[srcPos + 2];
  34766. byteArray[index + 1] = srcData[srcPos + 1];
  34767. byteArray[index + 2] = srcData[srcPos];
  34768. index += 3;
  34769. }
  34770. }
  34771. return byteArray;
  34772. };
  34773. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34774. var byteArray = new Uint8Array(dataLength);
  34775. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34776. var index = 0;
  34777. for (var y = 0; y < height; y++) {
  34778. for (var x = 0; x < width; x++) {
  34779. var srcPos = (x + y * width);
  34780. byteArray[index] = srcData[srcPos];
  34781. index++;
  34782. }
  34783. }
  34784. return byteArray;
  34785. };
  34786. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  34787. if (lodIndex === void 0) { lodIndex = -1; }
  34788. var ext = engine.getCaps().s3tc;
  34789. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  34790. if (header[off_magic] != DDS_MAGIC) {
  34791. BABYLON.Tools.Error("Invalid magic number in DDS header");
  34792. return;
  34793. }
  34794. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  34795. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  34796. return;
  34797. }
  34798. if (info.isCompressed && !ext) {
  34799. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  34800. return;
  34801. }
  34802. var bpp = header[off_RGBbpp];
  34803. dataOffset = header[off_size] + 4;
  34804. var computeFormats = false;
  34805. if (info.isFourCC) {
  34806. fourCC = header[off_pfFourCC];
  34807. switch (fourCC) {
  34808. case FOURCC_DXT1:
  34809. blockBytes = 8;
  34810. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  34811. break;
  34812. case FOURCC_DXT3:
  34813. blockBytes = 16;
  34814. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  34815. break;
  34816. case FOURCC_DXT5:
  34817. blockBytes = 16;
  34818. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  34819. break;
  34820. case FOURCC_D3DFMT_R16G16B16A16F:
  34821. computeFormats = true;
  34822. break;
  34823. case FOURCC_D3DFMT_R32G32B32A32F:
  34824. computeFormats = true;
  34825. break;
  34826. case FOURCC_DX10:
  34827. // There is an additionnal header so dataOffset need to be changed
  34828. dataOffset += 5 * 4; // 5 uints
  34829. var supported = false;
  34830. switch (info.dxgiFormat) {
  34831. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  34832. computeFormats = true;
  34833. supported = true;
  34834. break;
  34835. case DXGI_FORMAT_B8G8R8X8_UNORM:
  34836. info.isRGB = true;
  34837. info.isFourCC = false;
  34838. bpp = 32;
  34839. supported = true;
  34840. break;
  34841. }
  34842. if (supported) {
  34843. break;
  34844. }
  34845. default:
  34846. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  34847. return;
  34848. }
  34849. }
  34850. if (computeFormats) {
  34851. format = engine._getWebGLTextureType(info.textureType);
  34852. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34853. }
  34854. mipmapCount = 1;
  34855. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  34856. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34857. }
  34858. for (var face = 0; face < faces; face++) {
  34859. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34860. width = header[off_width];
  34861. height = header[off_height];
  34862. for (mip = 0; mip < mipmapCount; ++mip) {
  34863. if (lodIndex === -1 || lodIndex === mip) {
  34864. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  34865. var i = (lodIndex === -1) ? mip : 0;
  34866. if (!info.isCompressed && info.isFourCC) {
  34867. dataLength = width * height * 4;
  34868. var floatArray;
  34869. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  34870. if (bpp === 128) {
  34871. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34872. }
  34873. else if (bpp === 64) {
  34874. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34875. }
  34876. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34877. format = engine._getWebGLTextureType(info.textureType);
  34878. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34879. }
  34880. else {
  34881. if (bpp === 128) {
  34882. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34883. }
  34884. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  34885. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34886. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34887. format = engine._getWebGLTextureType(info.textureType);
  34888. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34889. }
  34890. else {
  34891. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34892. }
  34893. }
  34894. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  34895. }
  34896. else if (info.isRGB) {
  34897. if (bpp === 24) {
  34898. dataLength = width * height * 3;
  34899. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34900. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  34901. }
  34902. else {
  34903. dataLength = width * height * 4;
  34904. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34905. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  34906. }
  34907. }
  34908. else if (info.isLuminance) {
  34909. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  34910. var unpaddedRowSize = width;
  34911. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  34912. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  34913. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34914. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  34915. }
  34916. else {
  34917. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  34918. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  34919. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  34920. }
  34921. }
  34922. dataOffset += width * height * (bpp / 8);
  34923. width *= 0.5;
  34924. height *= 0.5;
  34925. width = Math.max(1.0, width);
  34926. height = Math.max(1.0, height);
  34927. }
  34928. }
  34929. };
  34930. DDSTools.StoreLODInAlphaChannel = false;
  34931. return DDSTools;
  34932. }());
  34933. Internals.DDSTools = DDSTools;
  34934. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34935. })(BABYLON || (BABYLON = {}));
  34936. //# sourceMappingURL=babylon.dds.js.map
  34937. var BABYLON;
  34938. (function (BABYLON) {
  34939. var Internals;
  34940. (function (Internals) {
  34941. /**
  34942. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  34943. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  34944. */
  34945. var KhronosTextureContainer = (function () {
  34946. /**
  34947. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  34948. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  34949. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  34950. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  34951. */
  34952. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  34953. this.arrayBuffer = arrayBuffer;
  34954. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  34955. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  34956. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  34957. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  34958. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  34959. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  34960. BABYLON.Tools.Error("texture missing KTX identifier");
  34961. return;
  34962. }
  34963. // load the reset of the header in native 32 bit int
  34964. var header = new Int32Array(this.arrayBuffer, 12, 13);
  34965. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  34966. var oppositeEndianess = header[0] === 0x01020304;
  34967. // read all the header elements in order they exist in the file, without modification (sans endainness)
  34968. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  34969. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  34970. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  34971. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  34972. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  34973. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  34974. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  34975. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  34976. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  34977. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  34978. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  34979. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  34980. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  34981. if (this.glType !== 0) {
  34982. BABYLON.Tools.Error("only compressed formats currently supported");
  34983. return;
  34984. }
  34985. else {
  34986. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  34987. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  34988. }
  34989. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  34990. BABYLON.Tools.Error("only 2D textures currently supported");
  34991. return;
  34992. }
  34993. if (this.numberOfArrayElements !== 0) {
  34994. BABYLON.Tools.Error("texture arrays not currently supported");
  34995. return;
  34996. }
  34997. if (this.numberOfFaces !== facesExpected) {
  34998. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  34999. return;
  35000. }
  35001. // we now have a completely validated file, so could use existence of loadType as success
  35002. // would need to make this more elaborate & adjust checks above to support more than one load type
  35003. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  35004. }
  35005. // not as fast hardware based, but will probably never need to use
  35006. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  35007. return ((val & 0xFF) << 24)
  35008. | ((val & 0xFF00) << 8)
  35009. | ((val >> 8) & 0xFF00)
  35010. | ((val >> 24) & 0xFF);
  35011. };
  35012. /**
  35013. * It is assumed that the texture has already been created & is currently bound
  35014. */
  35015. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  35016. switch (this.loadType) {
  35017. case KhronosTextureContainer.COMPRESSED_2D:
  35018. this._upload2DCompressedLevels(gl, loadMipmaps);
  35019. break;
  35020. case KhronosTextureContainer.TEX_2D:
  35021. case KhronosTextureContainer.COMPRESSED_3D:
  35022. case KhronosTextureContainer.TEX_3D:
  35023. }
  35024. };
  35025. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  35026. // initialize width & height for level 1
  35027. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  35028. var width = this.pixelWidth;
  35029. var height = this.pixelHeight;
  35030. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  35031. for (var level = 0; level < mipmapCount; level++) {
  35032. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  35033. for (var face = 0; face < this.numberOfFaces; face++) {
  35034. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  35035. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  35036. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  35037. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  35038. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  35039. }
  35040. width = Math.max(1.0, width * 0.5);
  35041. height = Math.max(1.0, height * 0.5);
  35042. }
  35043. };
  35044. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  35045. // load types
  35046. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  35047. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  35048. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  35049. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  35050. return KhronosTextureContainer;
  35051. }());
  35052. Internals.KhronosTextureContainer = KhronosTextureContainer;
  35053. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35054. })(BABYLON || (BABYLON = {}));
  35055. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  35056. var BABYLON;
  35057. (function (BABYLON) {
  35058. var PostProcess = (function () {
  35059. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  35060. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  35061. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35062. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  35063. if (blockCompilation === void 0) { blockCompilation = false; }
  35064. this.name = name;
  35065. this.width = -1;
  35066. this.height = -1;
  35067. this.autoClear = true;
  35068. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  35069. /*
  35070. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  35071. Can only be used on a single postprocess or on the last one of a chain.
  35072. */
  35073. this.enablePixelPerfectMode = false;
  35074. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  35075. this.alwaysForcePOT = false;
  35076. this.samples = 1;
  35077. this._reusable = false;
  35078. this._textures = new BABYLON.SmartArray(2);
  35079. this._currentRenderTextureInd = 0;
  35080. this._scaleRatio = new BABYLON.Vector2(1, 1);
  35081. this._texelSize = BABYLON.Vector2.Zero();
  35082. // Events
  35083. /**
  35084. * An event triggered when the postprocess is activated.
  35085. * @type {BABYLON.Observable}
  35086. */
  35087. this.onActivateObservable = new BABYLON.Observable();
  35088. /**
  35089. * An event triggered when the postprocess changes its size.
  35090. * @type {BABYLON.Observable}
  35091. */
  35092. this.onSizeChangedObservable = new BABYLON.Observable();
  35093. /**
  35094. * An event triggered when the postprocess applies its effect.
  35095. * @type {BABYLON.Observable}
  35096. */
  35097. this.onApplyObservable = new BABYLON.Observable();
  35098. /**
  35099. * An event triggered before rendering the postprocess
  35100. * @type {BABYLON.Observable}
  35101. */
  35102. this.onBeforeRenderObservable = new BABYLON.Observable();
  35103. /**
  35104. * An event triggered after rendering the postprocess
  35105. * @type {BABYLON.Observable}
  35106. */
  35107. this.onAfterRenderObservable = new BABYLON.Observable();
  35108. if (camera != null) {
  35109. this._camera = camera;
  35110. this._scene = camera.getScene();
  35111. camera.attachPostProcess(this);
  35112. this._engine = this._scene.getEngine();
  35113. this._scene.postProcesses.push(this);
  35114. }
  35115. else {
  35116. this._engine = engine;
  35117. this._engine.postProcesses.push(this);
  35118. }
  35119. this._options = options;
  35120. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  35121. this._reusable = reusable || false;
  35122. this._textureType = textureType;
  35123. this._samplers = samplers || [];
  35124. this._samplers.push("textureSampler");
  35125. this._fragmentUrl = fragmentUrl;
  35126. this._vertexUrl = vertexUrl;
  35127. this._parameters = parameters || [];
  35128. this._parameters.push("scale");
  35129. this._indexParameters = indexParameters;
  35130. if (!blockCompilation) {
  35131. this.updateEffect(defines);
  35132. }
  35133. }
  35134. Object.defineProperty(PostProcess.prototype, "onActivate", {
  35135. set: function (callback) {
  35136. if (this._onActivateObserver) {
  35137. this.onActivateObservable.remove(this._onActivateObserver);
  35138. }
  35139. this._onActivateObserver = this.onActivateObservable.add(callback);
  35140. },
  35141. enumerable: true,
  35142. configurable: true
  35143. });
  35144. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  35145. set: function (callback) {
  35146. if (this._onSizeChangedObserver) {
  35147. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  35148. }
  35149. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  35150. },
  35151. enumerable: true,
  35152. configurable: true
  35153. });
  35154. Object.defineProperty(PostProcess.prototype, "onApply", {
  35155. set: function (callback) {
  35156. if (this._onApplyObserver) {
  35157. this.onApplyObservable.remove(this._onApplyObserver);
  35158. }
  35159. this._onApplyObserver = this.onApplyObservable.add(callback);
  35160. },
  35161. enumerable: true,
  35162. configurable: true
  35163. });
  35164. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  35165. set: function (callback) {
  35166. if (this._onBeforeRenderObserver) {
  35167. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  35168. }
  35169. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  35170. },
  35171. enumerable: true,
  35172. configurable: true
  35173. });
  35174. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  35175. set: function (callback) {
  35176. if (this._onAfterRenderObserver) {
  35177. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  35178. }
  35179. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  35180. },
  35181. enumerable: true,
  35182. configurable: true
  35183. });
  35184. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  35185. get: function () {
  35186. return this._textures.data[this._currentRenderTextureInd];
  35187. },
  35188. set: function (value) {
  35189. this._forcedOutputTexture = value;
  35190. },
  35191. enumerable: true,
  35192. configurable: true
  35193. });
  35194. PostProcess.prototype.getCamera = function () {
  35195. return this._camera;
  35196. };
  35197. Object.defineProperty(PostProcess.prototype, "texelSize", {
  35198. get: function () {
  35199. if (this._shareOutputWithPostProcess) {
  35200. return this._shareOutputWithPostProcess.texelSize;
  35201. }
  35202. if (this._forcedOutputTexture) {
  35203. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  35204. }
  35205. return this._texelSize;
  35206. },
  35207. enumerable: true,
  35208. configurable: true
  35209. });
  35210. PostProcess.prototype.getEngine = function () {
  35211. return this._engine;
  35212. };
  35213. PostProcess.prototype.getEffect = function () {
  35214. return this._effect;
  35215. };
  35216. PostProcess.prototype.shareOutputWith = function (postProcess) {
  35217. this._disposeTextures();
  35218. this._shareOutputWithPostProcess = postProcess;
  35219. return this;
  35220. };
  35221. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  35222. 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);
  35223. };
  35224. PostProcess.prototype.isReusable = function () {
  35225. return this._reusable;
  35226. };
  35227. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  35228. PostProcess.prototype.markTextureDirty = function () {
  35229. this.width = -1;
  35230. };
  35231. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  35232. var _this = this;
  35233. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  35234. camera = camera || this._camera;
  35235. var scene = camera.getScene();
  35236. var engine = scene.getEngine();
  35237. var maxSize = engine.getCaps().maxTextureSize;
  35238. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  35239. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  35240. var desiredWidth = this._options.width || requiredWidth;
  35241. var desiredHeight = this._options.height || requiredHeight;
  35242. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  35243. if (!this._options.width) {
  35244. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  35245. }
  35246. if (!this._options.height) {
  35247. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  35248. }
  35249. }
  35250. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  35251. if (this._textures.length > 0) {
  35252. for (var i = 0; i < this._textures.length; i++) {
  35253. this._engine._releaseTexture(this._textures.data[i]);
  35254. }
  35255. this._textures.reset();
  35256. }
  35257. this.width = desiredWidth;
  35258. this.height = desiredHeight;
  35259. var textureSize = { width: this.width, height: this.height };
  35260. var textureOptions = {
  35261. generateMipMaps: false,
  35262. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  35263. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  35264. samplingMode: this.renderTargetSamplingMode,
  35265. type: this._textureType
  35266. };
  35267. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35268. if (this._reusable) {
  35269. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35270. }
  35271. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  35272. this.onSizeChangedObservable.notifyObservers(this);
  35273. }
  35274. this._textures.forEach(function (texture) {
  35275. if (texture.samples !== _this.samples) {
  35276. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  35277. }
  35278. });
  35279. }
  35280. var target;
  35281. if (this._shareOutputWithPostProcess) {
  35282. target = this._shareOutputWithPostProcess.outputTexture;
  35283. }
  35284. else if (this._forcedOutputTexture) {
  35285. target = this._forcedOutputTexture;
  35286. this.width = this._forcedOutputTexture.width;
  35287. this.height = this._forcedOutputTexture.height;
  35288. }
  35289. else {
  35290. target = this.outputTexture;
  35291. }
  35292. if (this.enablePixelPerfectMode) {
  35293. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  35294. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  35295. }
  35296. else {
  35297. this._scaleRatio.copyFromFloats(1, 1);
  35298. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  35299. }
  35300. this.onActivateObservable.notifyObservers(camera);
  35301. // Clear
  35302. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  35303. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  35304. }
  35305. if (this._reusable) {
  35306. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  35307. }
  35308. };
  35309. Object.defineProperty(PostProcess.prototype, "isSupported", {
  35310. get: function () {
  35311. return this._effect.isSupported;
  35312. },
  35313. enumerable: true,
  35314. configurable: true
  35315. });
  35316. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  35317. get: function () {
  35318. if (this._shareOutputWithPostProcess) {
  35319. return this._shareOutputWithPostProcess.aspectRatio;
  35320. }
  35321. if (this._forcedOutputTexture) {
  35322. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  35323. }
  35324. return this.width / this.height;
  35325. },
  35326. enumerable: true,
  35327. configurable: true
  35328. });
  35329. PostProcess.prototype.apply = function () {
  35330. // Check
  35331. if (!this._effect || !this._effect.isReady())
  35332. return null;
  35333. // States
  35334. this._engine.enableEffect(this._effect);
  35335. this._engine.setState(false);
  35336. this._engine.setDepthBuffer(false);
  35337. this._engine.setDepthWrite(false);
  35338. // Alpha
  35339. this._engine.setAlphaMode(this.alphaMode);
  35340. if (this.alphaConstants) {
  35341. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  35342. }
  35343. // Texture
  35344. var source;
  35345. if (this._shareOutputWithPostProcess) {
  35346. source = this._shareOutputWithPostProcess.outputTexture;
  35347. }
  35348. else if (this._forcedOutputTexture) {
  35349. source = this._forcedOutputTexture;
  35350. }
  35351. else {
  35352. source = this.outputTexture;
  35353. }
  35354. this._effect._bindTexture("textureSampler", source);
  35355. // Parameters
  35356. this._effect.setVector2("scale", this._scaleRatio);
  35357. this.onApplyObservable.notifyObservers(this._effect);
  35358. return this._effect;
  35359. };
  35360. PostProcess.prototype._disposeTextures = function () {
  35361. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  35362. return;
  35363. }
  35364. if (this._textures.length > 0) {
  35365. for (var i = 0; i < this._textures.length; i++) {
  35366. this._engine._releaseTexture(this._textures.data[i]);
  35367. }
  35368. }
  35369. this._textures.dispose();
  35370. };
  35371. PostProcess.prototype.dispose = function (camera) {
  35372. camera = camera || this._camera;
  35373. this._disposeTextures();
  35374. if (this._scene) {
  35375. var index_1 = this._scene.postProcesses.indexOf(this);
  35376. if (index_1 !== -1) {
  35377. this._scene.postProcesses.splice(index_1, 1);
  35378. }
  35379. }
  35380. else {
  35381. var index_2 = this._engine.postProcesses.indexOf(this);
  35382. if (index_2 !== -1) {
  35383. this._engine.postProcesses.splice(index_2, 1);
  35384. }
  35385. }
  35386. if (!camera) {
  35387. return;
  35388. }
  35389. camera.detachPostProcess(this);
  35390. var index = camera._postProcesses.indexOf(this);
  35391. if (index === 0 && camera._postProcesses.length > 0) {
  35392. this._camera._postProcesses[0].markTextureDirty();
  35393. }
  35394. this.onActivateObservable.clear();
  35395. this.onAfterRenderObservable.clear();
  35396. this.onApplyObservable.clear();
  35397. this.onBeforeRenderObservable.clear();
  35398. this.onSizeChangedObservable.clear();
  35399. };
  35400. return PostProcess;
  35401. }());
  35402. BABYLON.PostProcess = PostProcess;
  35403. })(BABYLON || (BABYLON = {}));
  35404. //# sourceMappingURL=babylon.postProcess.js.map
  35405. var BABYLON;
  35406. (function (BABYLON) {
  35407. var PassPostProcess = (function (_super) {
  35408. __extends(PassPostProcess, _super);
  35409. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  35410. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35411. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  35412. }
  35413. return PassPostProcess;
  35414. }(BABYLON.PostProcess));
  35415. BABYLON.PassPostProcess = PassPostProcess;
  35416. })(BABYLON || (BABYLON = {}));
  35417. //# sourceMappingURL=babylon.passPostProcess.js.map
  35418. var BABYLON;
  35419. (function (BABYLON) {
  35420. var ShadowGenerator = (function () {
  35421. /**
  35422. * Creates a ShadowGenerator object.
  35423. * A ShadowGenerator is the required tool to use the shadows.
  35424. * Each light casting shadows needs to use its own ShadowGenerator.
  35425. * Required parameters :
  35426. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  35427. * - `light`: the light object generating the shadows.
  35428. * - `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.
  35429. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  35430. */
  35431. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  35432. // Members
  35433. this._bias = 0.00005;
  35434. this._blurBoxOffset = 1;
  35435. this._blurScale = 2;
  35436. this._blurKernel = 1;
  35437. this._useKernelBlur = false;
  35438. this._filter = ShadowGenerator.FILTER_NONE;
  35439. this._darkness = 0;
  35440. this._transparencyShadow = false;
  35441. /**
  35442. * Controls the extent to which the shadows fade out at the edge of the frustum
  35443. * Used only by directionals and spots
  35444. */
  35445. this.frustumEdgeFalloff = 0;
  35446. this.forceBackFacesOnly = false;
  35447. this._lightDirection = BABYLON.Vector3.Zero();
  35448. this._viewMatrix = BABYLON.Matrix.Zero();
  35449. this._projectionMatrix = BABYLON.Matrix.Zero();
  35450. this._transformMatrix = BABYLON.Matrix.Zero();
  35451. this._worldViewProjection = BABYLON.Matrix.Zero();
  35452. this._currentFaceIndex = 0;
  35453. this._currentFaceIndexCache = 0;
  35454. this._isCube = false;
  35455. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  35456. this._mapSize = mapSize;
  35457. this._light = light;
  35458. this._scene = light.getScene();
  35459. light._shadowGenerator = this;
  35460. // Texture type fallback from float to int if not supported.
  35461. var caps = this._scene.getEngine().getCaps();
  35462. if (!useFullFloatFirst) {
  35463. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  35464. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  35465. }
  35466. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  35467. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  35468. }
  35469. else {
  35470. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  35471. }
  35472. }
  35473. else {
  35474. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  35475. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  35476. }
  35477. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  35478. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  35479. }
  35480. else {
  35481. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  35482. }
  35483. }
  35484. this._initializeGenerator();
  35485. }
  35486. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  35487. // Static
  35488. get: function () {
  35489. return ShadowGenerator._FILTER_NONE;
  35490. },
  35491. enumerable: true,
  35492. configurable: true
  35493. });
  35494. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  35495. get: function () {
  35496. return ShadowGenerator._FILTER_POISSONSAMPLING;
  35497. },
  35498. enumerable: true,
  35499. configurable: true
  35500. });
  35501. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  35502. get: function () {
  35503. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  35504. },
  35505. enumerable: true,
  35506. configurable: true
  35507. });
  35508. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  35509. get: function () {
  35510. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  35511. },
  35512. enumerable: true,
  35513. configurable: true
  35514. });
  35515. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  35516. get: function () {
  35517. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  35518. },
  35519. enumerable: true,
  35520. configurable: true
  35521. });
  35522. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  35523. get: function () {
  35524. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  35525. },
  35526. enumerable: true,
  35527. configurable: true
  35528. });
  35529. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  35530. get: function () {
  35531. return this._bias;
  35532. },
  35533. set: function (bias) {
  35534. this._bias = bias;
  35535. },
  35536. enumerable: true,
  35537. configurable: true
  35538. });
  35539. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  35540. get: function () {
  35541. return this._blurBoxOffset;
  35542. },
  35543. set: function (value) {
  35544. if (this._blurBoxOffset === value) {
  35545. return;
  35546. }
  35547. this._blurBoxOffset = value;
  35548. this._disposeBlurPostProcesses();
  35549. },
  35550. enumerable: true,
  35551. configurable: true
  35552. });
  35553. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  35554. get: function () {
  35555. return this._blurScale;
  35556. },
  35557. set: function (value) {
  35558. if (this._blurScale === value) {
  35559. return;
  35560. }
  35561. this._blurScale = value;
  35562. this._disposeBlurPostProcesses();
  35563. },
  35564. enumerable: true,
  35565. configurable: true
  35566. });
  35567. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  35568. get: function () {
  35569. return this._blurKernel;
  35570. },
  35571. set: function (value) {
  35572. if (this._blurKernel === value) {
  35573. return;
  35574. }
  35575. this._blurKernel = value;
  35576. this._disposeBlurPostProcesses();
  35577. },
  35578. enumerable: true,
  35579. configurable: true
  35580. });
  35581. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  35582. get: function () {
  35583. return this._useKernelBlur;
  35584. },
  35585. set: function (value) {
  35586. if (this._useKernelBlur === value) {
  35587. return;
  35588. }
  35589. this._useKernelBlur = value;
  35590. this._disposeBlurPostProcesses();
  35591. },
  35592. enumerable: true,
  35593. configurable: true
  35594. });
  35595. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  35596. get: function () {
  35597. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  35598. },
  35599. set: function (value) {
  35600. this._depthScale = value;
  35601. },
  35602. enumerable: true,
  35603. configurable: true
  35604. });
  35605. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  35606. get: function () {
  35607. return this._filter;
  35608. },
  35609. set: function (value) {
  35610. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  35611. if (this._light.needCube()) {
  35612. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  35613. this.useExponentialShadowMap = true;
  35614. return;
  35615. }
  35616. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  35617. this.useCloseExponentialShadowMap = true;
  35618. return;
  35619. }
  35620. }
  35621. if (this._filter === value) {
  35622. return;
  35623. }
  35624. this._filter = value;
  35625. this._disposeBlurPostProcesses();
  35626. this._applyFilterValues();
  35627. this._light._markMeshesAsLightDirty();
  35628. },
  35629. enumerable: true,
  35630. configurable: true
  35631. });
  35632. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  35633. get: function () {
  35634. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  35635. },
  35636. set: function (value) {
  35637. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  35638. return;
  35639. }
  35640. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  35641. },
  35642. enumerable: true,
  35643. configurable: true
  35644. });
  35645. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  35646. get: function () {
  35647. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  35648. return this.useExponentialShadowMap;
  35649. },
  35650. set: function (value) {
  35651. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  35652. this.useExponentialShadowMap = value;
  35653. },
  35654. enumerable: true,
  35655. configurable: true
  35656. });
  35657. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  35658. get: function () {
  35659. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  35660. return this.useBlurExponentialShadowMap;
  35661. },
  35662. set: function (value) {
  35663. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  35664. this.useBlurExponentialShadowMap = value;
  35665. },
  35666. enumerable: true,
  35667. configurable: true
  35668. });
  35669. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  35670. get: function () {
  35671. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  35672. },
  35673. set: function (value) {
  35674. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  35675. return;
  35676. }
  35677. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35678. },
  35679. enumerable: true,
  35680. configurable: true
  35681. });
  35682. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  35683. get: function () {
  35684. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  35685. },
  35686. set: function (value) {
  35687. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  35688. return;
  35689. }
  35690. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35691. },
  35692. enumerable: true,
  35693. configurable: true
  35694. });
  35695. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  35696. get: function () {
  35697. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  35698. },
  35699. set: function (value) {
  35700. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  35701. return;
  35702. }
  35703. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35704. },
  35705. enumerable: true,
  35706. configurable: true
  35707. });
  35708. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  35709. get: function () {
  35710. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  35711. },
  35712. set: function (value) {
  35713. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  35714. return;
  35715. }
  35716. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35717. },
  35718. enumerable: true,
  35719. configurable: true
  35720. });
  35721. /**
  35722. * Returns the darkness value (float).
  35723. */
  35724. ShadowGenerator.prototype.getDarkness = function () {
  35725. return this._darkness;
  35726. };
  35727. /**
  35728. * Sets the ShadowGenerator darkness value (float <= 1.0).
  35729. * Returns the ShadowGenerator.
  35730. */
  35731. ShadowGenerator.prototype.setDarkness = function (darkness) {
  35732. if (darkness >= 1.0)
  35733. this._darkness = 1.0;
  35734. else if (darkness <= 0.0)
  35735. this._darkness = 0.0;
  35736. else
  35737. this._darkness = darkness;
  35738. return this;
  35739. };
  35740. /**
  35741. * Sets the ability to have transparent shadow (boolean).
  35742. * Returns the ShadowGenerator.
  35743. */
  35744. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  35745. this._transparencyShadow = hasShadow;
  35746. return this;
  35747. };
  35748. /**
  35749. * Returns a RenderTargetTexture object : the shadow map texture.
  35750. */
  35751. ShadowGenerator.prototype.getShadowMap = function () {
  35752. return this._shadowMap;
  35753. };
  35754. /**
  35755. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  35756. */
  35757. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  35758. if (this._shadowMap2) {
  35759. return this._shadowMap2;
  35760. }
  35761. return this._shadowMap;
  35762. };
  35763. /**
  35764. * Returns the associated light object.
  35765. */
  35766. ShadowGenerator.prototype.getLight = function () {
  35767. return this._light;
  35768. };
  35769. ShadowGenerator.prototype._initializeGenerator = function () {
  35770. this._light._markMeshesAsLightDirty();
  35771. this._initializeShadowMap();
  35772. };
  35773. ShadowGenerator.prototype._initializeShadowMap = function () {
  35774. var _this = this;
  35775. // Render target
  35776. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  35777. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35778. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35779. this._shadowMap.anisotropicFilteringLevel = 1;
  35780. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35781. this._shadowMap.renderParticles = false;
  35782. // Record Face Index before render.
  35783. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  35784. _this._currentFaceIndex = faceIndex;
  35785. });
  35786. // Custom render function.
  35787. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  35788. // Blur if required afer render.
  35789. this._shadowMap.onAfterUnbindObservable.add(function () {
  35790. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  35791. return;
  35792. }
  35793. if (!_this._blurPostProcesses) {
  35794. _this._initializeBlurRTTAndPostProcesses();
  35795. }
  35796. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  35797. });
  35798. // Clear according to the chosen filter.
  35799. this._shadowMap.onClearObservable.add(function (engine) {
  35800. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  35801. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  35802. }
  35803. else {
  35804. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  35805. }
  35806. });
  35807. };
  35808. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  35809. var _this = this;
  35810. var engine = this._scene.getEngine();
  35811. var targetSize = this._mapSize / this.blurScale;
  35812. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  35813. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  35814. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35815. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35816. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35817. }
  35818. if (this.useKernelBlur) {
  35819. 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);
  35820. this._kernelBlurXPostprocess.width = targetSize;
  35821. this._kernelBlurXPostprocess.height = targetSize;
  35822. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  35823. effect.setTexture("textureSampler", _this._shadowMap);
  35824. });
  35825. 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);
  35826. this._kernelBlurXPostprocess.autoClear = false;
  35827. this._kernelBlurYPostprocess.autoClear = false;
  35828. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  35829. this._kernelBlurXPostprocess.packedFloat = true;
  35830. this._kernelBlurYPostprocess.packedFloat = true;
  35831. }
  35832. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  35833. }
  35834. else {
  35835. 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);
  35836. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  35837. effect.setFloat2("screenSize", targetSize, targetSize);
  35838. effect.setTexture("textureSampler", _this._shadowMap);
  35839. });
  35840. this._boxBlurPostprocess.autoClear = false;
  35841. this._blurPostProcesses = [this._boxBlurPostprocess];
  35842. }
  35843. };
  35844. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35845. var index;
  35846. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35847. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  35848. }
  35849. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35850. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  35851. }
  35852. if (this._transparencyShadow) {
  35853. for (index = 0; index < transparentSubMeshes.length; index++) {
  35854. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  35855. }
  35856. }
  35857. };
  35858. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  35859. var _this = this;
  35860. var mesh = subMesh.getRenderingMesh();
  35861. var scene = this._scene;
  35862. var engine = scene.getEngine();
  35863. // Culling
  35864. engine.setState(subMesh.getMaterial().backFaceCulling);
  35865. // Managing instances
  35866. var batch = mesh._getInstancesRenderList(subMesh._id);
  35867. if (batch.mustReturn) {
  35868. return;
  35869. }
  35870. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  35871. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  35872. engine.enableEffect(this._effect);
  35873. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  35874. var material = subMesh.getMaterial();
  35875. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  35876. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  35877. this._effect.setVector3("lightPosition", this.getLight().position);
  35878. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  35879. // Alpha test
  35880. if (material && material.needAlphaTesting()) {
  35881. var alphaTexture = material.getAlphaTestTexture();
  35882. if (alphaTexture) {
  35883. this._effect.setTexture("diffuseSampler", alphaTexture);
  35884. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  35885. }
  35886. }
  35887. // Bones
  35888. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35889. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35890. }
  35891. if (this.forceBackFacesOnly) {
  35892. engine.setState(true, 0, false, true);
  35893. }
  35894. // Draw
  35895. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35896. if (this.forceBackFacesOnly) {
  35897. engine.setState(true, 0, false, false);
  35898. }
  35899. }
  35900. else {
  35901. // Need to reset refresh rate of the shadowMap
  35902. this._shadowMap.resetRefreshCounter();
  35903. }
  35904. };
  35905. ShadowGenerator.prototype._applyFilterValues = function () {
  35906. if (this.filter === ShadowGenerator.FILTER_NONE) {
  35907. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  35908. }
  35909. else {
  35910. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35911. }
  35912. };
  35913. /**
  35914. * Force shader compilation including textures ready check
  35915. */
  35916. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  35917. var _this = this;
  35918. var scene = this._scene;
  35919. var engine = scene.getEngine();
  35920. var subMeshes = new Array();
  35921. var currentIndex = 0;
  35922. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  35923. var mesh = _a[_i];
  35924. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  35925. }
  35926. var checkReady = function () {
  35927. if (!_this._scene || !_this._scene.getEngine()) {
  35928. return;
  35929. }
  35930. var subMesh = subMeshes[currentIndex];
  35931. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  35932. currentIndex++;
  35933. if (currentIndex >= subMeshes.length) {
  35934. if (onCompiled) {
  35935. onCompiled(_this);
  35936. }
  35937. return;
  35938. }
  35939. }
  35940. setTimeout(checkReady, 16);
  35941. };
  35942. if (subMeshes.length > 0) {
  35943. checkReady();
  35944. }
  35945. };
  35946. /**
  35947. * Boolean : true when the ShadowGenerator is finally computed.
  35948. */
  35949. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  35950. var defines = [];
  35951. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  35952. defines.push("#define FLOAT");
  35953. }
  35954. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  35955. defines.push("#define ESM");
  35956. }
  35957. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35958. var mesh = subMesh.getMesh();
  35959. var material = subMesh.getMaterial();
  35960. // Alpha test
  35961. if (material && material.needAlphaTesting()) {
  35962. var alphaTexture = material.getAlphaTestTexture();
  35963. if (alphaTexture) {
  35964. defines.push("#define ALPHATEST");
  35965. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35966. attribs.push(BABYLON.VertexBuffer.UVKind);
  35967. defines.push("#define UV1");
  35968. }
  35969. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35970. if (alphaTexture.coordinatesIndex === 1) {
  35971. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35972. defines.push("#define UV2");
  35973. }
  35974. }
  35975. }
  35976. }
  35977. // Bones
  35978. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35979. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35980. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35981. if (mesh.numBoneInfluencers > 4) {
  35982. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35983. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35984. }
  35985. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35986. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35987. }
  35988. else {
  35989. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35990. }
  35991. // Instances
  35992. if (useInstances) {
  35993. defines.push("#define INSTANCES");
  35994. attribs.push("world0");
  35995. attribs.push("world1");
  35996. attribs.push("world2");
  35997. attribs.push("world3");
  35998. }
  35999. // Get correct effect
  36000. var join = defines.join("\n");
  36001. if (this._cachedDefines !== join) {
  36002. this._cachedDefines = join;
  36003. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  36004. }
  36005. return this._effect.isReady();
  36006. };
  36007. /**
  36008. * This creates the defines related to the standard BJS materials.
  36009. */
  36010. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  36011. var scene = this._scene;
  36012. var light = this._light;
  36013. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  36014. return;
  36015. }
  36016. defines["SHADOW" + lightIndex] = true;
  36017. if (this.usePoissonSampling) {
  36018. defines["SHADOWPCF" + lightIndex] = true;
  36019. }
  36020. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  36021. defines["SHADOWESM" + lightIndex] = true;
  36022. }
  36023. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  36024. defines["SHADOWCLOSEESM" + lightIndex] = true;
  36025. }
  36026. if (light.needCube()) {
  36027. defines["SHADOWCUBE" + lightIndex] = true;
  36028. }
  36029. };
  36030. /**
  36031. * This binds shadow lights related to the standard BJS materials.
  36032. * It implies the unifroms available on the materials are the standard BJS ones.
  36033. */
  36034. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  36035. var light = this._light;
  36036. var scene = this._scene;
  36037. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  36038. return;
  36039. }
  36040. if (!light.needCube()) {
  36041. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  36042. }
  36043. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  36044. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  36045. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  36046. };
  36047. // Methods
  36048. /**
  36049. * Returns a Matrix object : the updated transformation matrix.
  36050. */
  36051. ShadowGenerator.prototype.getTransformMatrix = function () {
  36052. var scene = this._scene;
  36053. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  36054. return this._transformMatrix;
  36055. }
  36056. this._currentRenderID = scene.getRenderId();
  36057. this._currentFaceIndexCache = this._currentFaceIndex;
  36058. var lightPosition = this._light.position;
  36059. if (this._light.computeTransformedInformation()) {
  36060. lightPosition = this._light.transformedPosition;
  36061. }
  36062. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  36063. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  36064. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  36065. }
  36066. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  36067. this._cachedPosition = lightPosition.clone();
  36068. this._cachedDirection = this._lightDirection.clone();
  36069. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  36070. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  36071. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  36072. }
  36073. return this._transformMatrix;
  36074. };
  36075. ShadowGenerator.prototype.recreateShadowMap = function () {
  36076. // Track render list.
  36077. var renderList = this._shadowMap.renderList;
  36078. // Clean up existing data.
  36079. this._disposeRTTandPostProcesses();
  36080. // Reinitializes.
  36081. this._initializeGenerator();
  36082. // Reaffect the filter to ensure a correct fallback if necessary.
  36083. this.filter = this.filter;
  36084. // Reaffect the filter.
  36085. this._applyFilterValues();
  36086. // Reaffect Render List.
  36087. this._shadowMap.renderList = renderList;
  36088. };
  36089. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  36090. if (this._shadowMap2) {
  36091. this._shadowMap2.dispose();
  36092. this._shadowMap2 = null;
  36093. }
  36094. if (this._downSamplePostprocess) {
  36095. this._downSamplePostprocess.dispose();
  36096. this._downSamplePostprocess = null;
  36097. }
  36098. if (this._boxBlurPostprocess) {
  36099. this._boxBlurPostprocess.dispose();
  36100. this._boxBlurPostprocess = null;
  36101. }
  36102. if (this._kernelBlurXPostprocess) {
  36103. this._kernelBlurXPostprocess.dispose();
  36104. this._kernelBlurXPostprocess = null;
  36105. }
  36106. if (this._kernelBlurYPostprocess) {
  36107. this._kernelBlurYPostprocess.dispose();
  36108. this._kernelBlurYPostprocess = null;
  36109. }
  36110. this._blurPostProcesses = null;
  36111. };
  36112. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  36113. if (this._shadowMap) {
  36114. this._shadowMap.dispose();
  36115. this._shadowMap = null;
  36116. }
  36117. this._disposeBlurPostProcesses();
  36118. };
  36119. /**
  36120. * Disposes the ShadowGenerator.
  36121. * Returns nothing.
  36122. */
  36123. ShadowGenerator.prototype.dispose = function () {
  36124. this._disposeRTTandPostProcesses();
  36125. this._light._shadowGenerator = null;
  36126. this._light._markMeshesAsLightDirty();
  36127. };
  36128. /**
  36129. * Serializes the ShadowGenerator and returns a serializationObject.
  36130. */
  36131. ShadowGenerator.prototype.serialize = function () {
  36132. var serializationObject = {};
  36133. var shadowMap = this.getShadowMap();
  36134. serializationObject.lightId = this._light.id;
  36135. serializationObject.mapSize = shadowMap.getRenderSize();
  36136. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  36137. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  36138. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  36139. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  36140. serializationObject.usePoissonSampling = this.usePoissonSampling;
  36141. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  36142. serializationObject.depthScale = this.depthScale;
  36143. serializationObject.darkness = this.getDarkness();
  36144. serializationObject.blurBoxOffset = this.blurBoxOffset;
  36145. serializationObject.blurKernel = this.blurKernel;
  36146. serializationObject.blurScale = this.blurScale;
  36147. serializationObject.useKernelBlur = this.useKernelBlur;
  36148. serializationObject.transparencyShadow = this._transparencyShadow;
  36149. serializationObject.renderList = [];
  36150. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  36151. var mesh = shadowMap.renderList[meshIndex];
  36152. serializationObject.renderList.push(mesh.id);
  36153. }
  36154. return serializationObject;
  36155. };
  36156. /**
  36157. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  36158. */
  36159. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  36160. //casting to point light, as light is missing the position attr and typescript complains.
  36161. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  36162. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  36163. var shadowMap = shadowGenerator.getShadowMap();
  36164. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  36165. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  36166. meshes.forEach(function (mesh) {
  36167. shadowMap.renderList.push(mesh);
  36168. });
  36169. }
  36170. if (parsedShadowGenerator.usePoissonSampling) {
  36171. shadowGenerator.usePoissonSampling = true;
  36172. }
  36173. else if (parsedShadowGenerator.useExponentialShadowMap) {
  36174. shadowGenerator.useExponentialShadowMap = true;
  36175. }
  36176. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  36177. shadowGenerator.useBlurExponentialShadowMap = true;
  36178. }
  36179. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  36180. shadowGenerator.useCloseExponentialShadowMap = true;
  36181. }
  36182. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  36183. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  36184. }
  36185. else if (parsedShadowGenerator.useVarianceShadowMap) {
  36186. shadowGenerator.useExponentialShadowMap = true;
  36187. }
  36188. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  36189. shadowGenerator.useBlurExponentialShadowMap = true;
  36190. }
  36191. if (parsedShadowGenerator.depthScale) {
  36192. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  36193. }
  36194. if (parsedShadowGenerator.blurScale) {
  36195. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  36196. }
  36197. if (parsedShadowGenerator.blurBoxOffset) {
  36198. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  36199. }
  36200. if (parsedShadowGenerator.useKernelBlur) {
  36201. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  36202. }
  36203. if (parsedShadowGenerator.blurKernel) {
  36204. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  36205. }
  36206. if (parsedShadowGenerator.bias !== undefined) {
  36207. shadowGenerator.bias = parsedShadowGenerator.bias;
  36208. }
  36209. if (parsedShadowGenerator.darkness) {
  36210. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  36211. }
  36212. if (parsedShadowGenerator.transparencyShadow) {
  36213. shadowGenerator.setTransparencyShadow(true);
  36214. }
  36215. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  36216. return shadowGenerator;
  36217. };
  36218. ShadowGenerator._FILTER_NONE = 0;
  36219. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  36220. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  36221. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  36222. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  36223. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  36224. return ShadowGenerator;
  36225. }());
  36226. BABYLON.ShadowGenerator = ShadowGenerator;
  36227. })(BABYLON || (BABYLON = {}));
  36228. //# sourceMappingURL=babylon.shadowGenerator.js.map
  36229. var BABYLON;
  36230. (function (BABYLON) {
  36231. var ShadowLight = (function (_super) {
  36232. __extends(ShadowLight, _super);
  36233. function ShadowLight() {
  36234. var _this = _super !== null && _super.apply(this, arguments) || this;
  36235. _this._needProjectionMatrixCompute = true;
  36236. return _this;
  36237. }
  36238. Object.defineProperty(ShadowLight.prototype, "direction", {
  36239. get: function () {
  36240. return this._direction;
  36241. },
  36242. set: function (value) {
  36243. this._direction = value;
  36244. },
  36245. enumerable: true,
  36246. configurable: true
  36247. });
  36248. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  36249. get: function () {
  36250. return this._shadowMinZ;
  36251. },
  36252. set: function (value) {
  36253. this._shadowMinZ = value;
  36254. this.forceProjectionMatrixCompute();
  36255. },
  36256. enumerable: true,
  36257. configurable: true
  36258. });
  36259. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  36260. get: function () {
  36261. return this._shadowMaxZ;
  36262. },
  36263. set: function (value) {
  36264. this._shadowMaxZ = value;
  36265. this.forceProjectionMatrixCompute();
  36266. },
  36267. enumerable: true,
  36268. configurable: true
  36269. });
  36270. /**
  36271. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  36272. */
  36273. ShadowLight.prototype.computeTransformedInformation = function () {
  36274. if (this.parent && this.parent.getWorldMatrix) {
  36275. if (!this.transformedPosition) {
  36276. this.transformedPosition = BABYLON.Vector3.Zero();
  36277. }
  36278. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  36279. // In case the direction is present.
  36280. if (this.direction) {
  36281. if (!this.transformedDirection) {
  36282. this.transformedDirection = BABYLON.Vector3.Zero();
  36283. }
  36284. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  36285. }
  36286. return true;
  36287. }
  36288. return false;
  36289. };
  36290. /**
  36291. * Return the depth scale used for the shadow map.
  36292. */
  36293. ShadowLight.prototype.getDepthScale = function () {
  36294. return 50.0;
  36295. };
  36296. /**
  36297. * Returns the light direction (Vector3) for any passed face index.
  36298. */
  36299. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  36300. return this.transformedDirection ? this.transformedDirection : this.direction;
  36301. };
  36302. /**
  36303. * Returns the DirectionalLight absolute position in the World.
  36304. */
  36305. ShadowLight.prototype.getAbsolutePosition = function () {
  36306. return this.transformedPosition ? this.transformedPosition : this.position;
  36307. };
  36308. /**
  36309. * Sets the DirectionalLight direction toward the passed target (Vector3).
  36310. * Returns the updated DirectionalLight direction (Vector3).
  36311. */
  36312. ShadowLight.prototype.setDirectionToTarget = function (target) {
  36313. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  36314. return this.direction;
  36315. };
  36316. /**
  36317. * Returns the light rotation (Vector3).
  36318. */
  36319. ShadowLight.prototype.getRotation = function () {
  36320. this.direction.normalize();
  36321. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  36322. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  36323. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  36324. };
  36325. /**
  36326. * Boolean : false by default.
  36327. */
  36328. ShadowLight.prototype.needCube = function () {
  36329. return false;
  36330. };
  36331. /**
  36332. * Specifies wether or not the projection matrix should be recomputed this frame.
  36333. */
  36334. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  36335. return this._needProjectionMatrixCompute;
  36336. };
  36337. /**
  36338. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  36339. */
  36340. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  36341. this._needProjectionMatrixCompute = true;
  36342. };
  36343. /**
  36344. * Get the world matrix of the sahdow lights.
  36345. */
  36346. ShadowLight.prototype._getWorldMatrix = function () {
  36347. if (!this._worldMatrix) {
  36348. this._worldMatrix = BABYLON.Matrix.Identity();
  36349. }
  36350. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  36351. return this._worldMatrix;
  36352. };
  36353. /**
  36354. * Gets the minZ used for shadow according to both the scene and the light.
  36355. * @param activeCamera
  36356. */
  36357. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  36358. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  36359. };
  36360. /**
  36361. * Gets the maxZ used for shadow according to both the scene and the light.
  36362. * @param activeCamera
  36363. */
  36364. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  36365. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  36366. };
  36367. /**
  36368. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  36369. * Returns the light.
  36370. */
  36371. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36372. if (this.customProjectionMatrixBuilder) {
  36373. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  36374. }
  36375. else {
  36376. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36377. }
  36378. return this;
  36379. };
  36380. __decorate([
  36381. BABYLON.serializeAsVector3()
  36382. ], ShadowLight.prototype, "position", void 0);
  36383. __decorate([
  36384. BABYLON.serializeAsVector3()
  36385. ], ShadowLight.prototype, "direction", null);
  36386. __decorate([
  36387. BABYLON.serialize()
  36388. ], ShadowLight.prototype, "shadowMinZ", null);
  36389. __decorate([
  36390. BABYLON.serialize()
  36391. ], ShadowLight.prototype, "shadowMaxZ", null);
  36392. return ShadowLight;
  36393. }(BABYLON.Light));
  36394. BABYLON.ShadowLight = ShadowLight;
  36395. })(BABYLON || (BABYLON = {}));
  36396. //# sourceMappingURL=babylon.shadowLight.js.map
  36397. var BABYLON;
  36398. (function (BABYLON) {
  36399. var PointLight = (function (_super) {
  36400. __extends(PointLight, _super);
  36401. /**
  36402. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  36403. * A PointLight emits the light in every direction.
  36404. * It can cast shadows.
  36405. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  36406. * ```javascript
  36407. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  36408. * ```
  36409. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36410. */
  36411. function PointLight(name, position, scene) {
  36412. var _this = _super.call(this, name, scene) || this;
  36413. _this._shadowAngle = Math.PI / 2;
  36414. _this.position = position;
  36415. return _this;
  36416. }
  36417. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  36418. /**
  36419. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36420. * This specifies what angle the shadow will use to be created.
  36421. *
  36422. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36423. */
  36424. get: function () {
  36425. return this._shadowAngle;
  36426. },
  36427. /**
  36428. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36429. * This specifies what angle the shadow will use to be created.
  36430. *
  36431. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36432. */
  36433. set: function (value) {
  36434. this._shadowAngle = value;
  36435. this.forceProjectionMatrixCompute();
  36436. },
  36437. enumerable: true,
  36438. configurable: true
  36439. });
  36440. Object.defineProperty(PointLight.prototype, "direction", {
  36441. get: function () {
  36442. return this._direction;
  36443. },
  36444. /**
  36445. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36446. */
  36447. set: function (value) {
  36448. var previousNeedCube = this.needCube();
  36449. this._direction = value;
  36450. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  36451. this._shadowGenerator.recreateShadowMap();
  36452. }
  36453. },
  36454. enumerable: true,
  36455. configurable: true
  36456. });
  36457. /**
  36458. * Returns the string "PointLight"
  36459. */
  36460. PointLight.prototype.getClassName = function () {
  36461. return "PointLight";
  36462. };
  36463. /**
  36464. * Returns the integer 0.
  36465. */
  36466. PointLight.prototype.getTypeID = function () {
  36467. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  36468. };
  36469. /**
  36470. * Specifies wether or not the shadowmap should be a cube texture.
  36471. */
  36472. PointLight.prototype.needCube = function () {
  36473. return !this.direction;
  36474. };
  36475. /**
  36476. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  36477. */
  36478. PointLight.prototype.getShadowDirection = function (faceIndex) {
  36479. if (this.direction) {
  36480. return _super.prototype.getShadowDirection.call(this, faceIndex);
  36481. }
  36482. else {
  36483. switch (faceIndex) {
  36484. case 0:
  36485. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  36486. case 1:
  36487. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  36488. case 2:
  36489. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  36490. case 3:
  36491. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  36492. case 4:
  36493. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  36494. case 5:
  36495. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  36496. }
  36497. }
  36498. return BABYLON.Vector3.Zero();
  36499. };
  36500. /**
  36501. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  36502. * - fov = PI / 2
  36503. * - aspect ratio : 1.0
  36504. * - z-near and far equal to the active camera minZ and maxZ.
  36505. * Returns the PointLight.
  36506. */
  36507. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36508. var activeCamera = this.getScene().activeCamera;
  36509. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36510. };
  36511. PointLight.prototype._buildUniformLayout = function () {
  36512. this._uniformBuffer.addUniform("vLightData", 4);
  36513. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36514. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36515. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36516. this._uniformBuffer.addUniform("depthValues", 2);
  36517. this._uniformBuffer.create();
  36518. };
  36519. /**
  36520. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  36521. * Returns the PointLight.
  36522. */
  36523. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  36524. if (this.computeTransformedInformation()) {
  36525. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  36526. return this;
  36527. }
  36528. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  36529. return this;
  36530. };
  36531. __decorate([
  36532. BABYLON.serialize()
  36533. ], PointLight.prototype, "shadowAngle", null);
  36534. return PointLight;
  36535. }(BABYLON.ShadowLight));
  36536. BABYLON.PointLight = PointLight;
  36537. })(BABYLON || (BABYLON = {}));
  36538. //# sourceMappingURL=babylon.pointLight.js.map
  36539. /// <reference path="babylon.light.ts" />
  36540. var BABYLON;
  36541. (function (BABYLON) {
  36542. var DirectionalLight = (function (_super) {
  36543. __extends(DirectionalLight, _super);
  36544. /**
  36545. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36546. * The directional light is emitted from everywhere in the given direction.
  36547. * It can cast shawdows.
  36548. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36549. */
  36550. function DirectionalLight(name, direction, scene) {
  36551. var _this = _super.call(this, name, scene) || this;
  36552. _this._shadowFrustumSize = 0;
  36553. _this._shadowOrthoScale = 0.5;
  36554. _this.autoUpdateExtends = true;
  36555. // Cache
  36556. _this._orthoLeft = Number.MAX_VALUE;
  36557. _this._orthoRight = Number.MIN_VALUE;
  36558. _this._orthoTop = Number.MIN_VALUE;
  36559. _this._orthoBottom = Number.MAX_VALUE;
  36560. _this.position = direction.scale(-1.0);
  36561. _this.direction = direction;
  36562. return _this;
  36563. }
  36564. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36565. /**
  36566. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36567. */
  36568. get: function () {
  36569. return this._shadowFrustumSize;
  36570. },
  36571. /**
  36572. * Specifies a fix frustum size for the shadow generation.
  36573. */
  36574. set: function (value) {
  36575. this._shadowFrustumSize = value;
  36576. this.forceProjectionMatrixCompute();
  36577. },
  36578. enumerable: true,
  36579. configurable: true
  36580. });
  36581. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36582. get: function () {
  36583. return this._shadowOrthoScale;
  36584. },
  36585. set: function (value) {
  36586. this._shadowOrthoScale = value;
  36587. this.forceProjectionMatrixCompute();
  36588. },
  36589. enumerable: true,
  36590. configurable: true
  36591. });
  36592. /**
  36593. * Returns the string "DirectionalLight".
  36594. */
  36595. DirectionalLight.prototype.getClassName = function () {
  36596. return "DirectionalLight";
  36597. };
  36598. /**
  36599. * Returns the integer 1.
  36600. */
  36601. DirectionalLight.prototype.getTypeID = function () {
  36602. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36603. };
  36604. /**
  36605. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36606. * Returns the DirectionalLight Shadow projection matrix.
  36607. */
  36608. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36609. if (this.shadowFrustumSize > 0) {
  36610. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36611. }
  36612. else {
  36613. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36614. }
  36615. };
  36616. /**
  36617. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36618. * Returns the DirectionalLight Shadow projection matrix.
  36619. */
  36620. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36621. var activeCamera = this.getScene().activeCamera;
  36622. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36623. };
  36624. /**
  36625. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36626. * Returns the DirectionalLight Shadow projection matrix.
  36627. */
  36628. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36629. var activeCamera = this.getScene().activeCamera;
  36630. // Check extends
  36631. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36632. var tempVector3 = BABYLON.Vector3.Zero();
  36633. this._orthoLeft = Number.MAX_VALUE;
  36634. this._orthoRight = Number.MIN_VALUE;
  36635. this._orthoTop = Number.MIN_VALUE;
  36636. this._orthoBottom = Number.MAX_VALUE;
  36637. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36638. var mesh = renderList[meshIndex];
  36639. if (!mesh) {
  36640. continue;
  36641. }
  36642. var boundingInfo = mesh.getBoundingInfo();
  36643. if (!boundingInfo) {
  36644. continue;
  36645. }
  36646. var boundingBox = boundingInfo.boundingBox;
  36647. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36648. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36649. if (tempVector3.x < this._orthoLeft)
  36650. this._orthoLeft = tempVector3.x;
  36651. if (tempVector3.y < this._orthoBottom)
  36652. this._orthoBottom = tempVector3.y;
  36653. if (tempVector3.x > this._orthoRight)
  36654. this._orthoRight = tempVector3.x;
  36655. if (tempVector3.y > this._orthoTop)
  36656. this._orthoTop = tempVector3.y;
  36657. }
  36658. }
  36659. }
  36660. var xOffset = this._orthoRight - this._orthoLeft;
  36661. var yOffset = this._orthoTop - this._orthoBottom;
  36662. 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);
  36663. };
  36664. DirectionalLight.prototype._buildUniformLayout = function () {
  36665. this._uniformBuffer.addUniform("vLightData", 4);
  36666. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36667. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36668. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36669. this._uniformBuffer.addUniform("depthValues", 2);
  36670. this._uniformBuffer.create();
  36671. };
  36672. /**
  36673. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  36674. * Returns the DirectionalLight.
  36675. */
  36676. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  36677. if (this.computeTransformedInformation()) {
  36678. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  36679. return this;
  36680. }
  36681. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  36682. return this;
  36683. };
  36684. /**
  36685. * Gets the minZ used for shadow according to both the scene and the light.
  36686. *
  36687. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36688. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36689. * @param activeCamera
  36690. */
  36691. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  36692. return 1;
  36693. };
  36694. /**
  36695. * Gets the maxZ used for shadow according to both the scene and the light.
  36696. *
  36697. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36698. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36699. * @param activeCamera
  36700. */
  36701. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  36702. return 1;
  36703. };
  36704. __decorate([
  36705. BABYLON.serialize()
  36706. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  36707. __decorate([
  36708. BABYLON.serialize()
  36709. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  36710. __decorate([
  36711. BABYLON.serialize()
  36712. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  36713. return DirectionalLight;
  36714. }(BABYLON.ShadowLight));
  36715. BABYLON.DirectionalLight = DirectionalLight;
  36716. })(BABYLON || (BABYLON = {}));
  36717. //# sourceMappingURL=babylon.directionalLight.js.map
  36718. var BABYLON;
  36719. (function (BABYLON) {
  36720. var SpotLight = (function (_super) {
  36721. __extends(SpotLight, _super);
  36722. /**
  36723. * Creates a SpotLight object in the scene with the passed parameters :
  36724. * - `position` (Vector3) is the initial SpotLight position,
  36725. * - `direction` (Vector3) is the initial SpotLight direction,
  36726. * - `angle` (float, in radians) is the spot light cone angle,
  36727. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  36728. * A spot light is a simply light oriented cone.
  36729. * It can cast shadows.
  36730. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36731. */
  36732. function SpotLight(name, position, direction, angle, exponent, scene) {
  36733. var _this = _super.call(this, name, scene) || this;
  36734. _this.position = position;
  36735. _this.direction = direction;
  36736. _this.angle = angle;
  36737. _this.exponent = exponent;
  36738. return _this;
  36739. }
  36740. Object.defineProperty(SpotLight.prototype, "angle", {
  36741. get: function () {
  36742. return this._angle;
  36743. },
  36744. set: function (value) {
  36745. this._angle = value;
  36746. this.forceProjectionMatrixCompute();
  36747. },
  36748. enumerable: true,
  36749. configurable: true
  36750. });
  36751. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  36752. get: function () {
  36753. return this._shadowAngleScale;
  36754. },
  36755. /**
  36756. * Allows scaling the angle of the light for shadow generation only.
  36757. */
  36758. set: function (value) {
  36759. this._shadowAngleScale = value;
  36760. this.forceProjectionMatrixCompute();
  36761. },
  36762. enumerable: true,
  36763. configurable: true
  36764. });
  36765. /**
  36766. * Returns the string "SpotLight".
  36767. */
  36768. SpotLight.prototype.getClassName = function () {
  36769. return "SpotLight";
  36770. };
  36771. /**
  36772. * Returns the integer 2.
  36773. */
  36774. SpotLight.prototype.getTypeID = function () {
  36775. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  36776. };
  36777. /**
  36778. * 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.
  36779. * Returns the SpotLight.
  36780. */
  36781. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36782. var activeCamera = this.getScene().activeCamera;
  36783. this._shadowAngleScale = this._shadowAngleScale || 1;
  36784. var angle = this._shadowAngleScale * this._angle;
  36785. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36786. };
  36787. SpotLight.prototype._buildUniformLayout = function () {
  36788. this._uniformBuffer.addUniform("vLightData", 4);
  36789. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36790. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36791. this._uniformBuffer.addUniform("vLightDirection", 3);
  36792. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36793. this._uniformBuffer.addUniform("depthValues", 2);
  36794. this._uniformBuffer.create();
  36795. };
  36796. /**
  36797. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  36798. * Return the SpotLight.
  36799. */
  36800. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  36801. var normalizeDirection;
  36802. if (this.computeTransformedInformation()) {
  36803. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  36804. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  36805. }
  36806. else {
  36807. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  36808. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36809. }
  36810. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  36811. return this;
  36812. };
  36813. __decorate([
  36814. BABYLON.serialize()
  36815. ], SpotLight.prototype, "angle", null);
  36816. __decorate([
  36817. BABYLON.serialize()
  36818. /**
  36819. * Allows scaling the angle of the light for shadow generation only.
  36820. */
  36821. ], SpotLight.prototype, "shadowAngleScale", null);
  36822. __decorate([
  36823. BABYLON.serialize()
  36824. ], SpotLight.prototype, "exponent", void 0);
  36825. return SpotLight;
  36826. }(BABYLON.ShadowLight));
  36827. BABYLON.SpotLight = SpotLight;
  36828. })(BABYLON || (BABYLON = {}));
  36829. //# sourceMappingURL=babylon.spotLight.js.map
  36830. var BABYLON;
  36831. (function (BABYLON) {
  36832. var MultiMaterial = (function (_super) {
  36833. __extends(MultiMaterial, _super);
  36834. function MultiMaterial(name, scene) {
  36835. var _this = _super.call(this, name, scene, true) || this;
  36836. scene.multiMaterials.push(_this);
  36837. _this.subMaterials = new Array();
  36838. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  36839. return _this;
  36840. }
  36841. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  36842. get: function () {
  36843. return this._subMaterials;
  36844. },
  36845. set: function (value) {
  36846. this._subMaterials = value;
  36847. this._hookArray(value);
  36848. },
  36849. enumerable: true,
  36850. configurable: true
  36851. });
  36852. MultiMaterial.prototype._hookArray = function (array) {
  36853. var _this = this;
  36854. var oldPush = array.push;
  36855. array.push = function () {
  36856. var items = [];
  36857. for (var _i = 0; _i < arguments.length; _i++) {
  36858. items[_i] = arguments[_i];
  36859. }
  36860. var result = oldPush.apply(array, items);
  36861. _this._markAllSubMeshesAsTexturesDirty();
  36862. return result;
  36863. };
  36864. var oldSplice = array.splice;
  36865. array.splice = function (index, deleteCount) {
  36866. var deleted = oldSplice.apply(array, [index, deleteCount]);
  36867. _this._markAllSubMeshesAsTexturesDirty();
  36868. return deleted;
  36869. };
  36870. };
  36871. // Properties
  36872. MultiMaterial.prototype.getSubMaterial = function (index) {
  36873. if (index < 0 || index >= this.subMaterials.length) {
  36874. return this.getScene().defaultMaterial;
  36875. }
  36876. return this.subMaterials[index];
  36877. };
  36878. MultiMaterial.prototype.getActiveTextures = function () {
  36879. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  36880. var _a;
  36881. };
  36882. // Methods
  36883. MultiMaterial.prototype.getClassName = function () {
  36884. return "MultiMaterial";
  36885. };
  36886. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36887. for (var index = 0; index < this.subMaterials.length; index++) {
  36888. var subMaterial = this.subMaterials[index];
  36889. if (subMaterial) {
  36890. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  36891. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  36892. return false;
  36893. }
  36894. continue;
  36895. }
  36896. if (!this.subMaterials[index].isReady(mesh)) {
  36897. return false;
  36898. }
  36899. }
  36900. }
  36901. return true;
  36902. };
  36903. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  36904. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  36905. for (var index = 0; index < this.subMaterials.length; index++) {
  36906. var subMaterial = null;
  36907. if (cloneChildren) {
  36908. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  36909. }
  36910. else {
  36911. subMaterial = this.subMaterials[index];
  36912. }
  36913. newMultiMaterial.subMaterials.push(subMaterial);
  36914. }
  36915. return newMultiMaterial;
  36916. };
  36917. MultiMaterial.prototype.serialize = function () {
  36918. var serializationObject = {};
  36919. serializationObject.name = this.name;
  36920. serializationObject.id = this.id;
  36921. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36922. serializationObject.materials = [];
  36923. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  36924. var subMat = this.subMaterials[matIndex];
  36925. if (subMat) {
  36926. serializationObject.materials.push(subMat.id);
  36927. }
  36928. else {
  36929. serializationObject.materials.push(null);
  36930. }
  36931. }
  36932. return serializationObject;
  36933. };
  36934. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36935. var scene = this.getScene();
  36936. if (!scene) {
  36937. return;
  36938. }
  36939. var index = scene.multiMaterials.indexOf(this);
  36940. if (index >= 0) {
  36941. scene.multiMaterials.splice(index, 1);
  36942. }
  36943. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36944. };
  36945. return MultiMaterial;
  36946. }(BABYLON.Material));
  36947. BABYLON.MultiMaterial = MultiMaterial;
  36948. })(BABYLON || (BABYLON = {}));
  36949. //# sourceMappingURL=babylon.multiMaterial.js.map
  36950. var BABYLON;
  36951. (function (BABYLON) {
  36952. var PBRMaterialDefines = (function (_super) {
  36953. __extends(PBRMaterialDefines, _super);
  36954. function PBRMaterialDefines() {
  36955. var _this = _super.call(this) || this;
  36956. _this.PBR = true;
  36957. _this.MAINUV1 = false;
  36958. _this.MAINUV2 = false;
  36959. _this.UV1 = false;
  36960. _this.UV2 = false;
  36961. _this.ALBEDO = false;
  36962. _this.ALBEDODIRECTUV = 0;
  36963. _this.VERTEXCOLOR = false;
  36964. _this.AMBIENT = false;
  36965. _this.AMBIENTDIRECTUV = 0;
  36966. _this.AMBIENTINGRAYSCALE = false;
  36967. _this.OPACITY = false;
  36968. _this.VERTEXALPHA = false;
  36969. _this.OPACITYDIRECTUV = 0;
  36970. _this.OPACITYRGB = false;
  36971. _this.ALPHATEST = false;
  36972. _this.ALPHABLEND = false;
  36973. _this.ALPHAFROMALBEDO = false;
  36974. _this.ALPHATESTVALUE = 0.5;
  36975. _this.SPECULAROVERALPHA = false;
  36976. _this.RADIANCEOVERALPHA = false;
  36977. _this.ALPHAFRESNEL = false;
  36978. _this.PREMULTIPLYALPHA = false;
  36979. _this.EMISSIVE = false;
  36980. _this.EMISSIVEDIRECTUV = 0;
  36981. _this.REFLECTIVITY = false;
  36982. _this.REFLECTIVITYDIRECTUV = 0;
  36983. _this.SPECULARTERM = false;
  36984. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36985. _this.MICROSURFACEAUTOMATIC = false;
  36986. _this.LODBASEDMICROSFURACE = false;
  36987. _this.MICROSURFACEMAP = false;
  36988. _this.MICROSURFACEMAPDIRECTUV = 0;
  36989. _this.METALLICWORKFLOW = false;
  36990. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36991. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36992. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36993. _this.AOSTOREINMETALMAPRED = false;
  36994. _this.ENVIRONMENTBRDF = false;
  36995. _this.NORMAL = false;
  36996. _this.TANGENT = false;
  36997. _this.BUMP = false;
  36998. _this.BUMPDIRECTUV = 0;
  36999. _this.PARALLAX = false;
  37000. _this.PARALLAXOCCLUSION = false;
  37001. _this.NORMALXYSCALE = true;
  37002. _this.LIGHTMAP = false;
  37003. _this.LIGHTMAPDIRECTUV = 0;
  37004. _this.USELIGHTMAPASSHADOWMAP = false;
  37005. _this.REFLECTION = false;
  37006. _this.REFLECTIONMAP_3D = false;
  37007. _this.REFLECTIONMAP_SPHERICAL = false;
  37008. _this.REFLECTIONMAP_PLANAR = false;
  37009. _this.REFLECTIONMAP_CUBIC = false;
  37010. _this.REFLECTIONMAP_PROJECTION = false;
  37011. _this.REFLECTIONMAP_SKYBOX = false;
  37012. _this.REFLECTIONMAP_EXPLICIT = false;
  37013. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37014. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37015. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37016. _this.INVERTCUBICMAP = false;
  37017. _this.USESPHERICALFROMREFLECTIONMAP = false;
  37018. _this.USESPHERICALINFRAGMENT = false;
  37019. _this.REFLECTIONMAP_OPPOSITEZ = false;
  37020. _this.LODINREFLECTIONALPHA = false;
  37021. _this.GAMMAREFLECTION = false;
  37022. _this.REFRACTION = false;
  37023. _this.REFRACTIONMAP_3D = false;
  37024. _this.REFRACTIONMAP_OPPOSITEZ = false;
  37025. _this.LODINREFRACTIONALPHA = false;
  37026. _this.GAMMAREFRACTION = false;
  37027. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  37028. _this.INSTANCES = false;
  37029. _this.NUM_BONE_INFLUENCERS = 0;
  37030. _this.BonesPerMesh = 0;
  37031. _this.MORPHTARGETS = false;
  37032. _this.MORPHTARGETS_NORMAL = false;
  37033. _this.MORPHTARGETS_TANGENT = false;
  37034. _this.NUM_MORPH_INFLUENCERS = 0;
  37035. _this.IMAGEPROCESSING = false;
  37036. _this.VIGNETTE = false;
  37037. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  37038. _this.VIGNETTEBLENDMODEOPAQUE = false;
  37039. _this.TONEMAPPING = false;
  37040. _this.CONTRAST = false;
  37041. _this.COLORCURVES = false;
  37042. _this.COLORGRADING = false;
  37043. _this.SAMPLER3DGREENDEPTH = false;
  37044. _this.SAMPLER3DBGRMAP = false;
  37045. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  37046. _this.EXPOSURE = false;
  37047. _this.USEPHYSICALLIGHTFALLOFF = false;
  37048. _this.TWOSIDEDLIGHTING = false;
  37049. _this.SHADOWFLOAT = false;
  37050. _this.USERIGHTHANDEDSYSTEM = false;
  37051. _this.CLIPPLANE = false;
  37052. _this.POINTSIZE = false;
  37053. _this.FOG = false;
  37054. _this.LOGARITHMICDEPTH = false;
  37055. _this.FORCENORMALFORWARD = false;
  37056. _this.rebuild();
  37057. return _this;
  37058. }
  37059. PBRMaterialDefines.prototype.reset = function () {
  37060. _super.prototype.reset.call(this);
  37061. this.ALPHATESTVALUE = 0.5;
  37062. this.PBR = true;
  37063. };
  37064. return PBRMaterialDefines;
  37065. }(BABYLON.MaterialDefines));
  37066. /**
  37067. * The Physically based material base class of BJS.
  37068. *
  37069. * This offers the main features of a standard PBR material.
  37070. * For more information, please refer to the documentation :
  37071. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37072. */
  37073. var PBRBaseMaterial = (function (_super) {
  37074. __extends(PBRBaseMaterial, _super);
  37075. /**
  37076. * Instantiates a new PBRMaterial instance.
  37077. *
  37078. * @param name The material name
  37079. * @param scene The scene the material will be use in.
  37080. */
  37081. function PBRBaseMaterial(name, scene) {
  37082. var _this = _super.call(this, name, scene) || this;
  37083. /**
  37084. * Intensity of the direct lights e.g. the four lights available in your scene.
  37085. * This impacts both the direct diffuse and specular highlights.
  37086. */
  37087. _this._directIntensity = 1.0;
  37088. /**
  37089. * Intensity of the emissive part of the material.
  37090. * This helps controlling the emissive effect without modifying the emissive color.
  37091. */
  37092. _this._emissiveIntensity = 1.0;
  37093. /**
  37094. * Intensity of the environment e.g. how much the environment will light the object
  37095. * either through harmonics for rough material or through the refelction for shiny ones.
  37096. */
  37097. _this._environmentIntensity = 1.0;
  37098. /**
  37099. * This is a special control allowing the reduction of the specular highlights coming from the
  37100. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37101. */
  37102. _this._specularIntensity = 1.0;
  37103. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  37104. /**
  37105. * Debug Control allowing disabling the bump map on this material.
  37106. */
  37107. _this._disableBumpMap = false;
  37108. /**
  37109. * AKA Occlusion Texture Intensity in other nomenclature.
  37110. */
  37111. _this._ambientTextureStrength = 1.0;
  37112. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  37113. /**
  37114. * AKA Diffuse Color in other nomenclature.
  37115. */
  37116. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  37117. /**
  37118. * AKA Specular Color in other nomenclature.
  37119. */
  37120. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37121. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  37122. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  37123. /**
  37124. * AKA Glossiness in other nomenclature.
  37125. */
  37126. _this._microSurface = 0.9;
  37127. /**
  37128. * source material index of refraction (IOR)' / 'destination material IOR.
  37129. */
  37130. _this._indexOfRefraction = 0.66;
  37131. /**
  37132. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37133. */
  37134. _this._invertRefractionY = false;
  37135. /**
  37136. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37137. * Materials half opaque for instance using refraction could benefit from this control.
  37138. */
  37139. _this._linkRefractionWithTransparency = false;
  37140. _this._useLightmapAsShadowmap = false;
  37141. /**
  37142. * Specifies that the alpha is coming form the albedo channel alpha channel.
  37143. */
  37144. _this._useAlphaFromAlbedoTexture = false;
  37145. /**
  37146. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37147. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37148. */
  37149. _this._useSpecularOverAlpha = true;
  37150. /**
  37151. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37152. */
  37153. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  37154. /**
  37155. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37156. */
  37157. _this._useRoughnessFromMetallicTextureAlpha = true;
  37158. /**
  37159. * Specifies if the metallic texture contains the roughness information in its green channel.
  37160. */
  37161. _this._useRoughnessFromMetallicTextureGreen = false;
  37162. /**
  37163. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37164. */
  37165. _this._useMetallnessFromMetallicTextureBlue = false;
  37166. /**
  37167. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37168. */
  37169. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  37170. /**
  37171. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37172. */
  37173. _this._useAmbientInGrayScale = false;
  37174. /**
  37175. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37176. * The material will try to infer what glossiness each pixel should be.
  37177. */
  37178. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  37179. /**
  37180. * BJS is using an harcoded light falloff based on a manually sets up range.
  37181. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37182. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37183. */
  37184. _this._usePhysicalLightFalloff = true;
  37185. /**
  37186. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37187. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37188. */
  37189. _this._useRadianceOverAlpha = true;
  37190. /**
  37191. * Allows using the bump map in parallax mode.
  37192. */
  37193. _this._useParallax = false;
  37194. /**
  37195. * Allows using the bump map in parallax occlusion mode.
  37196. */
  37197. _this._useParallaxOcclusion = false;
  37198. /**
  37199. * Controls the scale bias of the parallax mode.
  37200. */
  37201. _this._parallaxScaleBias = 0.05;
  37202. /**
  37203. * If sets to true, disables all the lights affecting the material.
  37204. */
  37205. _this._disableLighting = false;
  37206. /**
  37207. * Number of Simultaneous lights allowed on the material.
  37208. */
  37209. _this._maxSimultaneousLights = 4;
  37210. /**
  37211. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  37212. */
  37213. _this._invertNormalMapX = false;
  37214. /**
  37215. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  37216. */
  37217. _this._invertNormalMapY = false;
  37218. /**
  37219. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37220. */
  37221. _this._twoSidedLighting = false;
  37222. /**
  37223. * Defines the alpha limits in alpha test mode.
  37224. */
  37225. _this._alphaCutOff = 0.4;
  37226. /**
  37227. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37228. */
  37229. _this._forceAlphaTest = false;
  37230. /**
  37231. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  37232. * in your scene composition.
  37233. */
  37234. _this._preMultiplyAlpha = false;
  37235. /**
  37236. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37237. * And/Or occlude the blended part.
  37238. */
  37239. _this._useAlphaFresnel = false;
  37240. /**
  37241. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  37242. * from cos thetav and roughness:
  37243. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  37244. */
  37245. _this._environmentBRDFTexture = null;
  37246. /**
  37247. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37248. */
  37249. _this._forceIrradianceInFragment = false;
  37250. /**
  37251. * Force normal to face away from face.
  37252. * (Temporary internal fix to remove before 3.1)
  37253. */
  37254. _this._forceNormalForward = false;
  37255. _this._renderTargets = new BABYLON.SmartArray(16);
  37256. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  37257. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  37258. _this._tempColor = new BABYLON.Color3();
  37259. // Setup the default processing configuration to the scene.
  37260. _this._attachImageProcessingConfiguration(null);
  37261. _this.getRenderTargetTextures = function () {
  37262. _this._renderTargets.reset();
  37263. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  37264. _this._renderTargets.push(_this._reflectionTexture);
  37265. }
  37266. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  37267. _this._renderTargets.push(_this._refractionTexture);
  37268. }
  37269. return _this._renderTargets;
  37270. };
  37271. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37272. return _this;
  37273. }
  37274. /**
  37275. * Attaches a new image processing configuration to the PBR Material.
  37276. * @param configuration
  37277. */
  37278. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  37279. var _this = this;
  37280. if (configuration === this._imageProcessingConfiguration) {
  37281. return;
  37282. }
  37283. // Detaches observer.
  37284. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37285. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37286. }
  37287. // Pick the scene configuration if needed.
  37288. if (!configuration) {
  37289. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  37290. }
  37291. else {
  37292. this._imageProcessingConfiguration = configuration;
  37293. }
  37294. // Attaches observer.
  37295. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  37296. _this._markAllSubMeshesAsImageProcessingDirty();
  37297. });
  37298. };
  37299. PBRBaseMaterial.prototype.getClassName = function () {
  37300. return "PBRBaseMaterial";
  37301. };
  37302. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  37303. get: function () {
  37304. return this._useLogarithmicDepth;
  37305. },
  37306. set: function (value) {
  37307. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37308. },
  37309. enumerable: true,
  37310. configurable: true
  37311. });
  37312. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  37313. if (this._linkRefractionWithTransparency) {
  37314. return false;
  37315. }
  37316. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  37317. };
  37318. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  37319. if (this._forceAlphaTest) {
  37320. return true;
  37321. }
  37322. if (this._linkRefractionWithTransparency) {
  37323. return false;
  37324. }
  37325. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  37326. };
  37327. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  37328. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  37329. };
  37330. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  37331. return this._albedoTexture;
  37332. };
  37333. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37334. if (this.isFrozen) {
  37335. if (this._wasPreviouslyReady) {
  37336. return true;
  37337. }
  37338. }
  37339. if (!subMesh._materialDefines) {
  37340. subMesh._materialDefines = new PBRMaterialDefines();
  37341. }
  37342. var scene = this.getScene();
  37343. var defines = subMesh._materialDefines;
  37344. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37345. if (defines._renderId === scene.getRenderId()) {
  37346. return true;
  37347. }
  37348. }
  37349. var engine = scene.getEngine();
  37350. // Lights
  37351. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37352. defines._needNormals = true;
  37353. // Textures
  37354. if (defines._areTexturesDirty) {
  37355. defines._needUVs = false;
  37356. if (scene.texturesEnabled) {
  37357. if (scene.getEngine().getCaps().textureLOD) {
  37358. defines.LODBASEDMICROSFURACE = true;
  37359. }
  37360. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37361. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  37362. return false;
  37363. }
  37364. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  37365. }
  37366. else {
  37367. defines.ALBEDO = false;
  37368. }
  37369. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37370. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37371. return false;
  37372. }
  37373. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37374. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  37375. }
  37376. else {
  37377. defines.AMBIENT = false;
  37378. }
  37379. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37380. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37381. return false;
  37382. }
  37383. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37384. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37385. }
  37386. else {
  37387. defines.OPACITY = false;
  37388. }
  37389. var reflectionTexture = this._getReflectionTexture();
  37390. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37391. if (!reflectionTexture.isReadyOrNotBlocking()) {
  37392. return false;
  37393. }
  37394. defines.REFLECTION = true;
  37395. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  37396. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  37397. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37398. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  37399. defines.INVERTCUBICMAP = true;
  37400. }
  37401. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  37402. switch (reflectionTexture.coordinatesMode) {
  37403. case BABYLON.Texture.CUBIC_MODE:
  37404. case BABYLON.Texture.INVCUBIC_MODE:
  37405. defines.REFLECTIONMAP_CUBIC = true;
  37406. break;
  37407. case BABYLON.Texture.EXPLICIT_MODE:
  37408. defines.REFLECTIONMAP_EXPLICIT = true;
  37409. break;
  37410. case BABYLON.Texture.PLANAR_MODE:
  37411. defines.REFLECTIONMAP_PLANAR = true;
  37412. break;
  37413. case BABYLON.Texture.PROJECTION_MODE:
  37414. defines.REFLECTIONMAP_PROJECTION = true;
  37415. break;
  37416. case BABYLON.Texture.SKYBOX_MODE:
  37417. defines.REFLECTIONMAP_SKYBOX = true;
  37418. break;
  37419. case BABYLON.Texture.SPHERICAL_MODE:
  37420. defines.REFLECTIONMAP_SPHERICAL = true;
  37421. break;
  37422. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37423. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  37424. break;
  37425. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37426. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  37427. break;
  37428. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37429. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  37430. break;
  37431. }
  37432. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  37433. if (reflectionTexture.sphericalPolynomial) {
  37434. defines.USESPHERICALFROMREFLECTIONMAP = true;
  37435. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  37436. defines.USESPHERICALINFRAGMENT = true;
  37437. }
  37438. }
  37439. }
  37440. }
  37441. else {
  37442. defines.REFLECTION = false;
  37443. defines.REFLECTIONMAP_3D = false;
  37444. defines.REFLECTIONMAP_SPHERICAL = false;
  37445. defines.REFLECTIONMAP_PLANAR = false;
  37446. defines.REFLECTIONMAP_CUBIC = false;
  37447. defines.REFLECTIONMAP_PROJECTION = false;
  37448. defines.REFLECTIONMAP_SKYBOX = false;
  37449. defines.REFLECTIONMAP_EXPLICIT = false;
  37450. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37451. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37452. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37453. defines.INVERTCUBICMAP = false;
  37454. defines.USESPHERICALFROMREFLECTIONMAP = false;
  37455. defines.USESPHERICALINFRAGMENT = false;
  37456. defines.REFLECTIONMAP_OPPOSITEZ = false;
  37457. defines.LODINREFLECTIONALPHA = false;
  37458. defines.GAMMAREFLECTION = false;
  37459. }
  37460. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37461. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37462. return false;
  37463. }
  37464. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37465. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37466. }
  37467. else {
  37468. defines.LIGHTMAP = false;
  37469. }
  37470. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37471. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37472. return false;
  37473. }
  37474. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37475. }
  37476. else {
  37477. defines.EMISSIVE = false;
  37478. }
  37479. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37480. if (this._metallicTexture) {
  37481. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  37482. return false;
  37483. }
  37484. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  37485. defines.METALLICWORKFLOW = true;
  37486. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  37487. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  37488. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  37489. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  37490. }
  37491. else if (this._reflectivityTexture) {
  37492. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  37493. return false;
  37494. }
  37495. defines.METALLICWORKFLOW = false;
  37496. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  37497. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  37498. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  37499. }
  37500. else {
  37501. defines.METALLICWORKFLOW = false;
  37502. defines.REFLECTIVITY = false;
  37503. }
  37504. if (this._microSurfaceTexture) {
  37505. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  37506. return false;
  37507. }
  37508. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  37509. }
  37510. else {
  37511. defines.MICROSURFACEMAP = false;
  37512. }
  37513. }
  37514. else {
  37515. defines.REFLECTIVITY = false;
  37516. defines.MICROSURFACEMAP = false;
  37517. }
  37518. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37519. // Bump texure can not be none blocking.
  37520. if (!this._bumpTexture.isReady()) {
  37521. return false;
  37522. }
  37523. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37524. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37525. defines.PARALLAX = true;
  37526. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  37527. }
  37528. else {
  37529. defines.PARALLAX = false;
  37530. }
  37531. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  37532. }
  37533. else {
  37534. defines.BUMP = false;
  37535. }
  37536. var refractionTexture = this._getRefractionTexture();
  37537. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37538. if (!refractionTexture.isReadyOrNotBlocking()) {
  37539. return false;
  37540. }
  37541. defines.REFRACTION = true;
  37542. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  37543. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  37544. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  37545. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37546. if (this._linkRefractionWithTransparency) {
  37547. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  37548. }
  37549. }
  37550. else {
  37551. defines.REFRACTION = false;
  37552. }
  37553. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37554. // This is blocking.
  37555. if (!this._environmentBRDFTexture.isReady()) {
  37556. return false;
  37557. }
  37558. defines.ENVIRONMENTBRDF = true;
  37559. }
  37560. if (this._shouldUseAlphaFromAlbedoTexture()) {
  37561. defines.ALPHAFROMALBEDO = true;
  37562. }
  37563. }
  37564. if (this._useSpecularOverAlpha) {
  37565. defines.SPECULAROVERALPHA = true;
  37566. }
  37567. if (this._usePhysicalLightFalloff) {
  37568. defines.USEPHYSICALLIGHTFALLOFF = true;
  37569. }
  37570. if (this._useRadianceOverAlpha) {
  37571. defines.RADIANCEOVERALPHA = true;
  37572. }
  37573. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  37574. defines.METALLICWORKFLOW = true;
  37575. }
  37576. if (!this.backFaceCulling && this._twoSidedLighting) {
  37577. defines.TWOSIDEDLIGHTING = true;
  37578. }
  37579. defines.ALPHATESTVALUE = this._alphaCutOff;
  37580. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  37581. defines.ALPHABLEND = this.needAlphaBlending();
  37582. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  37583. }
  37584. if (defines._areImageProcessingDirty) {
  37585. if (!this._imageProcessingConfiguration.isReady()) {
  37586. return false;
  37587. }
  37588. this._imageProcessingConfiguration.prepareDefines(defines);
  37589. }
  37590. defines.FORCENORMALFORWARD = this._forceNormalForward;
  37591. // Misc.
  37592. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  37593. // Values that need to be evaluated on every frame
  37594. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  37595. // Attribs
  37596. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  37597. if (mesh) {
  37598. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37599. mesh.createNormals(true);
  37600. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  37601. }
  37602. }
  37603. }
  37604. // Get correct effect
  37605. if (defines.isDirty) {
  37606. defines.markAsProcessed();
  37607. scene.resetCachedMaterial();
  37608. // Fallbacks
  37609. var fallbacks = new BABYLON.EffectFallbacks();
  37610. if (defines.ENVIRONMENTBRDF) {
  37611. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  37612. }
  37613. if (defines.REFLECTION) {
  37614. fallbacks.addFallback(0, "REFLECTION");
  37615. }
  37616. if (defines.REFRACTION) {
  37617. fallbacks.addFallback(0, "REFRACTION");
  37618. }
  37619. if (defines.REFLECTIVITY) {
  37620. fallbacks.addFallback(0, "REFLECTIVITY");
  37621. }
  37622. if (defines.BUMP) {
  37623. fallbacks.addFallback(0, "BUMP");
  37624. }
  37625. if (defines.PARALLAX) {
  37626. fallbacks.addFallback(1, "PARALLAX");
  37627. }
  37628. if (defines.PARALLAXOCCLUSION) {
  37629. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  37630. }
  37631. if (defines.SPECULAROVERALPHA) {
  37632. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  37633. }
  37634. if (defines.FOG) {
  37635. fallbacks.addFallback(1, "FOG");
  37636. }
  37637. if (defines.POINTSIZE) {
  37638. fallbacks.addFallback(0, "POINTSIZE");
  37639. }
  37640. if (defines.LOGARITHMICDEPTH) {
  37641. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  37642. }
  37643. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  37644. if (defines.SPECULARTERM) {
  37645. fallbacks.addFallback(0, "SPECULARTERM");
  37646. }
  37647. if (defines.NUM_BONE_INFLUENCERS > 0) {
  37648. fallbacks.addCPUSkinningFallback(0, mesh);
  37649. }
  37650. //Attributes
  37651. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37652. if (defines.NORMAL) {
  37653. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37654. }
  37655. if (defines.TANGENT) {
  37656. attribs.push(BABYLON.VertexBuffer.TangentKind);
  37657. }
  37658. if (defines.UV1) {
  37659. attribs.push(BABYLON.VertexBuffer.UVKind);
  37660. }
  37661. if (defines.UV2) {
  37662. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37663. }
  37664. if (defines.VERTEXCOLOR) {
  37665. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37666. }
  37667. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37668. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37669. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37670. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  37671. "vFogInfos", "vFogColor", "pointSize",
  37672. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37673. "mBones",
  37674. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37675. "vLightingIntensity",
  37676. "logarithmicDepthConstant",
  37677. "vSphericalX", "vSphericalY", "vSphericalZ",
  37678. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  37679. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  37680. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  37681. "vNormalReoderParams"
  37682. ];
  37683. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  37684. "bumpSampler", "lightmapSampler", "opacitySampler",
  37685. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  37686. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  37687. "microSurfaceSampler", "environmentBrdfSampler"];
  37688. var uniformBuffers = ["Material", "Scene"];
  37689. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37690. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37691. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37692. uniformsNames: uniforms,
  37693. uniformBuffersNames: uniformBuffers,
  37694. samplers: samplers,
  37695. defines: defines,
  37696. maxSimultaneousLights: this._maxSimultaneousLights
  37697. });
  37698. var onCompiled = function (effect) {
  37699. if (this.onCompiled) {
  37700. this.onCompiled(effect);
  37701. }
  37702. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  37703. }.bind(this);
  37704. var join = defines.toString();
  37705. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  37706. attributes: attribs,
  37707. uniformsNames: uniforms,
  37708. uniformBuffersNames: uniformBuffers,
  37709. samplers: samplers,
  37710. defines: join,
  37711. fallbacks: fallbacks,
  37712. onCompiled: onCompiled,
  37713. onError: this.onError,
  37714. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37715. }, engine), defines);
  37716. this.buildUniformLayout();
  37717. }
  37718. if (!subMesh.effect.isReady()) {
  37719. return false;
  37720. }
  37721. defines._renderId = scene.getRenderId();
  37722. this._wasPreviouslyReady = true;
  37723. return true;
  37724. };
  37725. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  37726. // Order is important !
  37727. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  37728. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  37729. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37730. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37731. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37732. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  37733. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  37734. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37735. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37736. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37737. this._uniformBuffer.addUniform("albedoMatrix", 16);
  37738. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37739. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37740. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37741. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37742. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  37743. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  37744. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37745. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  37746. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37747. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37748. this._uniformBuffer.addUniform("vReflectionColor", 3);
  37749. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  37750. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  37751. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  37752. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  37753. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  37754. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37755. this._uniformBuffer.addUniform("pointSize", 1);
  37756. this._uniformBuffer.create();
  37757. };
  37758. PBRBaseMaterial.prototype.unbind = function () {
  37759. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37760. this._uniformBuffer.setTexture("reflectionSampler", null);
  37761. }
  37762. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37763. this._uniformBuffer.setTexture("refractionSampler", null);
  37764. }
  37765. _super.prototype.unbind.call(this);
  37766. };
  37767. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37768. this._activeEffect.setMatrix("world", world);
  37769. };
  37770. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37771. var scene = this.getScene();
  37772. var defines = subMesh._materialDefines;
  37773. if (!defines) {
  37774. return;
  37775. }
  37776. var effect = subMesh.effect;
  37777. this._activeEffect = effect;
  37778. // Matrices
  37779. this.bindOnlyWorldMatrix(world);
  37780. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37781. // Bones
  37782. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37783. if (mustRebind) {
  37784. this._uniformBuffer.bindToEffect(effect, "Material");
  37785. this.bindViewProjection(effect);
  37786. var reflectionTexture = this._getReflectionTexture();
  37787. var refractionTexture = this._getRefractionTexture();
  37788. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37789. // Texture uniforms
  37790. if (scene.texturesEnabled) {
  37791. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37792. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37793. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37794. }
  37795. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37796. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37797. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37798. }
  37799. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37800. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37801. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37802. }
  37803. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37804. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37805. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37806. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  37807. var polynomials = reflectionTexture.sphericalPolynomial;
  37808. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37809. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37810. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37811. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37812. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37813. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37814. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37815. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37816. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37817. }
  37818. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37819. }
  37820. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37821. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37822. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37823. }
  37824. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37825. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37826. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37827. }
  37828. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37829. if (this._metallicTexture) {
  37830. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37831. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37832. }
  37833. else if (this._reflectivityTexture) {
  37834. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37835. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37836. }
  37837. if (this._microSurfaceTexture) {
  37838. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37839. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37840. }
  37841. }
  37842. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37843. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37844. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37845. if (scene._mirroredCameraPosition) {
  37846. this._uniformBuffer.updateFloat4("vNormalReoderParams", this._invertNormalMapX ? 0 : 1.0, this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 0 : 1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37847. }
  37848. else {
  37849. this._uniformBuffer.updateFloat4("vNormalReoderParams", this._invertNormalMapX ? 1.0 : 0, this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? 1.0 : 0, this._invertNormalMapY ? -1.0 : 1.0);
  37850. }
  37851. }
  37852. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37853. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37854. var depth = 1.0;
  37855. if (!refractionTexture.isCube) {
  37856. if (refractionTexture.depth) {
  37857. depth = refractionTexture.depth;
  37858. }
  37859. }
  37860. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37861. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37862. }
  37863. }
  37864. // Point size
  37865. if (this.pointsCloud) {
  37866. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37867. }
  37868. // Colors
  37869. if (defines.METALLICWORKFLOW) {
  37870. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37871. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37872. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37873. }
  37874. else {
  37875. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37876. }
  37877. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37878. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37879. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37880. // Misc
  37881. this._lightingInfos.x = this._directIntensity;
  37882. this._lightingInfos.y = this._emissiveIntensity;
  37883. this._lightingInfos.z = this._environmentIntensity;
  37884. this._lightingInfos.w = this._specularIntensity;
  37885. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37886. }
  37887. // Textures
  37888. if (scene.texturesEnabled) {
  37889. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37890. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37891. }
  37892. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37893. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37894. }
  37895. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37896. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37897. }
  37898. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37899. if (defines.LODBASEDMICROSFURACE) {
  37900. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37901. }
  37902. else {
  37903. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37904. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37905. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37906. }
  37907. }
  37908. if (defines.ENVIRONMENTBRDF) {
  37909. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37910. }
  37911. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37912. if (defines.LODBASEDMICROSFURACE) {
  37913. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37914. }
  37915. else {
  37916. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37917. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37918. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37919. }
  37920. }
  37921. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37922. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37923. }
  37924. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37925. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37926. }
  37927. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37928. if (this._metallicTexture) {
  37929. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37930. }
  37931. else if (this._reflectivityTexture) {
  37932. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37933. }
  37934. if (this._microSurfaceTexture) {
  37935. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37936. }
  37937. }
  37938. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37939. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37940. }
  37941. }
  37942. // Clip plane
  37943. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37944. // Colors
  37945. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37946. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  37947. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  37948. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37949. }
  37950. if (mustRebind || !this.isFrozen) {
  37951. // Lights
  37952. if (scene.lightsEnabled && !this._disableLighting) {
  37953. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37954. }
  37955. // View
  37956. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37957. this.bindView(effect);
  37958. }
  37959. // Fog
  37960. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37961. // Morph targets
  37962. if (defines.NUM_MORPH_INFLUENCERS) {
  37963. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37964. }
  37965. // image processing
  37966. this._imageProcessingConfiguration.bind(this._activeEffect);
  37967. // Log. depth
  37968. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37969. }
  37970. this._uniformBuffer.update();
  37971. this._afterBind(mesh);
  37972. scene = null;
  37973. };
  37974. PBRBaseMaterial.prototype.getAnimatables = function () {
  37975. var results = [];
  37976. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37977. results.push(this._albedoTexture);
  37978. }
  37979. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37980. results.push(this._ambientTexture);
  37981. }
  37982. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37983. results.push(this._opacityTexture);
  37984. }
  37985. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37986. results.push(this._reflectionTexture);
  37987. }
  37988. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37989. results.push(this._emissiveTexture);
  37990. }
  37991. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37992. results.push(this._metallicTexture);
  37993. }
  37994. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37995. results.push(this._reflectivityTexture);
  37996. }
  37997. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37998. results.push(this._bumpTexture);
  37999. }
  38000. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  38001. results.push(this._lightmapTexture);
  38002. }
  38003. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  38004. results.push(this._refractionTexture);
  38005. }
  38006. return results;
  38007. };
  38008. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  38009. if (this._reflectionTexture) {
  38010. return this._reflectionTexture;
  38011. }
  38012. return this.getScene().environmentTexture;
  38013. };
  38014. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  38015. if (this._refractionTexture) {
  38016. return this._refractionTexture;
  38017. }
  38018. if (this._linkRefractionWithTransparency) {
  38019. return this.getScene().environmentTexture;
  38020. }
  38021. return null;
  38022. };
  38023. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38024. if (forceDisposeTextures) {
  38025. if (this._albedoTexture) {
  38026. this._albedoTexture.dispose();
  38027. }
  38028. if (this._ambientTexture) {
  38029. this._ambientTexture.dispose();
  38030. }
  38031. if (this._opacityTexture) {
  38032. this._opacityTexture.dispose();
  38033. }
  38034. if (this._reflectionTexture) {
  38035. this._reflectionTexture.dispose();
  38036. }
  38037. if (this._environmentBRDFTexture) {
  38038. this._environmentBRDFTexture.dispose();
  38039. }
  38040. if (this._emissiveTexture) {
  38041. this._emissiveTexture.dispose();
  38042. }
  38043. if (this._metallicTexture) {
  38044. this._metallicTexture.dispose();
  38045. }
  38046. if (this._reflectivityTexture) {
  38047. this._reflectivityTexture.dispose();
  38048. }
  38049. if (this._bumpTexture) {
  38050. this._bumpTexture.dispose();
  38051. }
  38052. if (this._lightmapTexture) {
  38053. this._lightmapTexture.dispose();
  38054. }
  38055. if (this._refractionTexture) {
  38056. this._refractionTexture.dispose();
  38057. }
  38058. }
  38059. this._renderTargets.dispose();
  38060. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38061. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38062. }
  38063. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38064. };
  38065. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  38066. __decorate([
  38067. BABYLON.serializeAsImageProcessingConfiguration()
  38068. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  38069. __decorate([
  38070. BABYLON.serialize()
  38071. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  38072. return PBRBaseMaterial;
  38073. }(BABYLON.PushMaterial));
  38074. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  38075. })(BABYLON || (BABYLON = {}));
  38076. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  38077. var BABYLON;
  38078. (function (BABYLON) {
  38079. var Internals;
  38080. (function (Internals) {
  38081. /**
  38082. * The Physically based simple base material of BJS.
  38083. *
  38084. * This enables better naming and convention enforcements on top of the pbrMaterial.
  38085. * It is used as the base class for both the specGloss and metalRough conventions.
  38086. */
  38087. var PBRBaseSimpleMaterial = (function (_super) {
  38088. __extends(PBRBaseSimpleMaterial, _super);
  38089. /**
  38090. * Instantiates a new PBRMaterial instance.
  38091. *
  38092. * @param name The material name
  38093. * @param scene The scene the material will be use in.
  38094. */
  38095. function PBRBaseSimpleMaterial(name, scene) {
  38096. var _this = _super.call(this, name, scene) || this;
  38097. /**
  38098. * Number of Simultaneous lights allowed on the material.
  38099. */
  38100. _this.maxSimultaneousLights = 4;
  38101. /**
  38102. * If sets to true, disables all the lights affecting the material.
  38103. */
  38104. _this.disableLighting = false;
  38105. /**
  38106. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38107. */
  38108. _this.invertNormalMapX = false;
  38109. /**
  38110. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38111. */
  38112. _this.invertNormalMapY = false;
  38113. /**
  38114. * Emissivie color used to self-illuminate the model.
  38115. */
  38116. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38117. /**
  38118. * Occlusion Channel Strenght.
  38119. */
  38120. _this.occlusionStrength = 1.0;
  38121. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38122. _this._useAmbientInGrayScale = true;
  38123. return _this;
  38124. }
  38125. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  38126. /**
  38127. * Gets the current transparency mode.
  38128. */
  38129. get: function () {
  38130. return this._transparencyMode;
  38131. },
  38132. /**
  38133. * Sets the transparency mode of the material.
  38134. */
  38135. set: function (value) {
  38136. if (this._transparencyMode === value) {
  38137. return;
  38138. }
  38139. this._transparencyMode = value;
  38140. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  38141. this._forceAlphaTest = true;
  38142. }
  38143. else {
  38144. this._forceAlphaTest = false;
  38145. }
  38146. this._markAllSubMeshesAsTexturesDirty();
  38147. },
  38148. enumerable: true,
  38149. configurable: true
  38150. });
  38151. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  38152. /**
  38153. * Gets the current double sided mode.
  38154. */
  38155. get: function () {
  38156. return this._twoSidedLighting;
  38157. },
  38158. /**
  38159. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38160. */
  38161. set: function (value) {
  38162. if (this._twoSidedLighting === value) {
  38163. return;
  38164. }
  38165. this._twoSidedLighting = value;
  38166. this.backFaceCulling = !value;
  38167. this._markAllSubMeshesAsTexturesDirty();
  38168. },
  38169. enumerable: true,
  38170. configurable: true
  38171. });
  38172. /**
  38173. * Specifies wether or not the alpha value of the albedo texture should be used.
  38174. */
  38175. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38176. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38177. };
  38178. /**
  38179. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  38180. */
  38181. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  38182. if (this._linkRefractionWithTransparency) {
  38183. return false;
  38184. }
  38185. return (this.alpha < 1.0) ||
  38186. (this._shouldUseAlphaFromAlbedoTexture() &&
  38187. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  38188. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  38189. };
  38190. /**
  38191. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  38192. */
  38193. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  38194. if (this._linkRefractionWithTransparency) {
  38195. return false;
  38196. }
  38197. return this._shouldUseAlphaFromAlbedoTexture() &&
  38198. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  38199. };
  38200. /**
  38201. * Return the active textures of the material.
  38202. */
  38203. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  38204. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38205. if (this.environmentTexture) {
  38206. activeTextures.push(this.environmentTexture);
  38207. }
  38208. if (this.normalTexture) {
  38209. activeTextures.push(this.normalTexture);
  38210. }
  38211. if (this.emissiveTexture) {
  38212. activeTextures.push(this.emissiveTexture);
  38213. }
  38214. if (this.occlusionTexture) {
  38215. activeTextures.push(this.occlusionTexture);
  38216. }
  38217. return activeTextures;
  38218. };
  38219. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  38220. return "PBRBaseSimpleMaterial";
  38221. };
  38222. __decorate([
  38223. BABYLON.serialize(),
  38224. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38225. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  38226. __decorate([
  38227. BABYLON.serialize(),
  38228. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38229. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  38230. __decorate([
  38231. BABYLON.serializeAsTexture(),
  38232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  38233. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  38234. __decorate([
  38235. BABYLON.serialize(),
  38236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38237. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  38238. __decorate([
  38239. BABYLON.serialize(),
  38240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38241. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  38242. __decorate([
  38243. BABYLON.serializeAsTexture(),
  38244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  38245. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  38246. __decorate([
  38247. BABYLON.serializeAsColor3("emissive"),
  38248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38249. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  38250. __decorate([
  38251. BABYLON.serializeAsTexture(),
  38252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38253. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  38254. __decorate([
  38255. BABYLON.serialize(),
  38256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  38257. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  38258. __decorate([
  38259. BABYLON.serializeAsTexture(),
  38260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  38261. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  38262. __decorate([
  38263. BABYLON.serialize(),
  38264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  38265. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  38266. __decorate([
  38267. BABYLON.serialize()
  38268. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  38269. __decorate([
  38270. BABYLON.serialize()
  38271. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  38272. return PBRBaseSimpleMaterial;
  38273. }(BABYLON.PBRBaseMaterial));
  38274. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  38275. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38276. })(BABYLON || (BABYLON = {}));
  38277. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  38278. var BABYLON;
  38279. (function (BABYLON) {
  38280. /**
  38281. * The Physically based material of BJS.
  38282. *
  38283. * This offers the main features of a standard PBR material.
  38284. * For more information, please refer to the documentation :
  38285. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38286. */
  38287. var PBRMaterial = (function (_super) {
  38288. __extends(PBRMaterial, _super);
  38289. /**
  38290. * Instantiates a new PBRMaterial instance.
  38291. *
  38292. * @param name The material name
  38293. * @param scene The scene the material will be use in.
  38294. */
  38295. function PBRMaterial(name, scene) {
  38296. var _this = _super.call(this, name, scene) || this;
  38297. /**
  38298. * Intensity of the direct lights e.g. the four lights available in your scene.
  38299. * This impacts both the direct diffuse and specular highlights.
  38300. */
  38301. _this.directIntensity = 1.0;
  38302. /**
  38303. * Intensity of the emissive part of the material.
  38304. * This helps controlling the emissive effect without modifying the emissive color.
  38305. */
  38306. _this.emissiveIntensity = 1.0;
  38307. /**
  38308. * Intensity of the environment e.g. how much the environment will light the object
  38309. * either through harmonics for rough material or through the refelction for shiny ones.
  38310. */
  38311. _this.environmentIntensity = 1.0;
  38312. /**
  38313. * This is a special control allowing the reduction of the specular highlights coming from the
  38314. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38315. */
  38316. _this.specularIntensity = 1.0;
  38317. /**
  38318. * Debug Control allowing disabling the bump map on this material.
  38319. */
  38320. _this.disableBumpMap = false;
  38321. /**
  38322. * AKA Occlusion Texture Intensity in other nomenclature.
  38323. */
  38324. _this.ambientTextureStrength = 1.0;
  38325. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38326. /**
  38327. * AKA Diffuse Color in other nomenclature.
  38328. */
  38329. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  38330. /**
  38331. * AKA Specular Color in other nomenclature.
  38332. */
  38333. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38334. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  38335. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38336. /**
  38337. * AKA Glossiness in other nomenclature.
  38338. */
  38339. _this.microSurface = 1.0;
  38340. /**
  38341. * source material index of refraction (IOR)' / 'destination material IOR.
  38342. */
  38343. _this.indexOfRefraction = 0.66;
  38344. /**
  38345. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38346. */
  38347. _this.invertRefractionY = false;
  38348. /**
  38349. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38350. * Materials half opaque for instance using refraction could benefit from this control.
  38351. */
  38352. _this.linkRefractionWithTransparency = false;
  38353. _this.useLightmapAsShadowmap = false;
  38354. /**
  38355. * Specifies that the alpha is coming form the albedo channel alpha channel.
  38356. */
  38357. _this.useAlphaFromAlbedoTexture = false;
  38358. /**
  38359. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38360. */
  38361. _this.forceAlphaTest = false;
  38362. /**
  38363. * Defines the alpha limits in alpha test mode.
  38364. */
  38365. _this.alphaCutOff = 0.4;
  38366. /**
  38367. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38368. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38369. */
  38370. _this.useSpecularOverAlpha = true;
  38371. /**
  38372. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38373. */
  38374. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  38375. /**
  38376. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38377. */
  38378. _this.useRoughnessFromMetallicTextureAlpha = true;
  38379. /**
  38380. * Specifies if the metallic texture contains the roughness information in its green channel.
  38381. */
  38382. _this.useRoughnessFromMetallicTextureGreen = false;
  38383. /**
  38384. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38385. */
  38386. _this.useMetallnessFromMetallicTextureBlue = false;
  38387. /**
  38388. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38389. */
  38390. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  38391. /**
  38392. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38393. */
  38394. _this.useAmbientInGrayScale = false;
  38395. /**
  38396. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38397. * The material will try to infer what glossiness each pixel should be.
  38398. */
  38399. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  38400. /**
  38401. * BJS is using an harcoded light falloff based on a manually sets up range.
  38402. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38403. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38404. */
  38405. _this.usePhysicalLightFalloff = true;
  38406. /**
  38407. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38408. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38409. */
  38410. _this.useRadianceOverAlpha = true;
  38411. /**
  38412. * Allows using the bump map in parallax mode.
  38413. */
  38414. _this.useParallax = false;
  38415. /**
  38416. * Allows using the bump map in parallax occlusion mode.
  38417. */
  38418. _this.useParallaxOcclusion = false;
  38419. /**
  38420. * Controls the scale bias of the parallax mode.
  38421. */
  38422. _this.parallaxScaleBias = 0.05;
  38423. /**
  38424. * If sets to true, disables all the lights affecting the material.
  38425. */
  38426. _this.disableLighting = false;
  38427. /**
  38428. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38429. */
  38430. _this.forceIrradianceInFragment = false;
  38431. /**
  38432. * Number of Simultaneous lights allowed on the material.
  38433. */
  38434. _this.maxSimultaneousLights = 4;
  38435. /**
  38436. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38437. */
  38438. _this.invertNormalMapX = false;
  38439. /**
  38440. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38441. */
  38442. _this.invertNormalMapY = false;
  38443. /**
  38444. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38445. */
  38446. _this.twoSidedLighting = false;
  38447. /**
  38448. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  38449. * in your scene composition.
  38450. */
  38451. _this.preMultiplyAlpha = false;
  38452. /**
  38453. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38454. * And/Or occlude the blended part.
  38455. */
  38456. _this.useAlphaFresnel = false;
  38457. /**
  38458. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38459. * And/Or occlude the blended part.
  38460. */
  38461. _this.environmentBRDFTexture = null;
  38462. /**
  38463. * Force normal to face away from face.
  38464. * (Temporary internal fix to remove before 3.1)
  38465. */
  38466. _this.forceNormalForward = false;
  38467. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38468. return _this;
  38469. }
  38470. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  38471. /**
  38472. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  38473. */
  38474. get: function () {
  38475. return this._PBRMATERIAL_OPAQUE;
  38476. },
  38477. enumerable: true,
  38478. configurable: true
  38479. });
  38480. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  38481. /**
  38482. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  38483. */
  38484. get: function () {
  38485. return this._PBRMATERIAL_ALPHATEST;
  38486. },
  38487. enumerable: true,
  38488. configurable: true
  38489. });
  38490. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  38491. /**
  38492. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38493. */
  38494. get: function () {
  38495. return this._PBRMATERIAL_ALPHABLEND;
  38496. },
  38497. enumerable: true,
  38498. configurable: true
  38499. });
  38500. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  38501. /**
  38502. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38503. * They are also discarded below the alpha cutoff threshold to improve performances.
  38504. */
  38505. get: function () {
  38506. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  38507. },
  38508. enumerable: true,
  38509. configurable: true
  38510. });
  38511. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  38512. /**
  38513. * Gets the image processing configuration used either in this material.
  38514. */
  38515. get: function () {
  38516. return this._imageProcessingConfiguration;
  38517. },
  38518. /**
  38519. * Sets the Default image processing configuration used either in the this material.
  38520. *
  38521. * If sets to null, the scene one is in use.
  38522. */
  38523. set: function (value) {
  38524. this._attachImageProcessingConfiguration(value);
  38525. // Ensure the effect will be rebuilt.
  38526. this._markAllSubMeshesAsTexturesDirty();
  38527. },
  38528. enumerable: true,
  38529. configurable: true
  38530. });
  38531. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  38532. /**
  38533. * Gets wether the color curves effect is enabled.
  38534. */
  38535. get: function () {
  38536. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38537. },
  38538. /**
  38539. * Sets wether the color curves effect is enabled.
  38540. */
  38541. set: function (value) {
  38542. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38543. },
  38544. enumerable: true,
  38545. configurable: true
  38546. });
  38547. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  38548. /**
  38549. * Gets wether the color grading effect is enabled.
  38550. */
  38551. get: function () {
  38552. return this.imageProcessingConfiguration.colorGradingEnabled;
  38553. },
  38554. /**
  38555. * Gets wether the color grading effect is enabled.
  38556. */
  38557. set: function (value) {
  38558. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38559. },
  38560. enumerable: true,
  38561. configurable: true
  38562. });
  38563. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  38564. /**
  38565. * Gets wether tonemapping is enabled or not.
  38566. */
  38567. get: function () {
  38568. return this._imageProcessingConfiguration.toneMappingEnabled;
  38569. },
  38570. /**
  38571. * Sets wether tonemapping is enabled or not
  38572. */
  38573. set: function (value) {
  38574. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38575. },
  38576. enumerable: true,
  38577. configurable: true
  38578. });
  38579. ;
  38580. ;
  38581. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  38582. /**
  38583. * The camera exposure used on this material.
  38584. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38585. * This corresponds to a photographic exposure.
  38586. */
  38587. get: function () {
  38588. return this._imageProcessingConfiguration.exposure;
  38589. },
  38590. /**
  38591. * The camera exposure used on this material.
  38592. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38593. * This corresponds to a photographic exposure.
  38594. */
  38595. set: function (value) {
  38596. this._imageProcessingConfiguration.exposure = value;
  38597. },
  38598. enumerable: true,
  38599. configurable: true
  38600. });
  38601. ;
  38602. ;
  38603. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  38604. /**
  38605. * Gets The camera contrast used on this material.
  38606. */
  38607. get: function () {
  38608. return this._imageProcessingConfiguration.contrast;
  38609. },
  38610. /**
  38611. * Sets The camera contrast used on this material.
  38612. */
  38613. set: function (value) {
  38614. this._imageProcessingConfiguration.contrast = value;
  38615. },
  38616. enumerable: true,
  38617. configurable: true
  38618. });
  38619. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  38620. /**
  38621. * Gets the Color Grading 2D Lookup Texture.
  38622. */
  38623. get: function () {
  38624. return this._imageProcessingConfiguration.colorGradingTexture;
  38625. },
  38626. /**
  38627. * Sets the Color Grading 2D Lookup Texture.
  38628. */
  38629. set: function (value) {
  38630. this._imageProcessingConfiguration.colorGradingTexture = value;
  38631. },
  38632. enumerable: true,
  38633. configurable: true
  38634. });
  38635. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  38636. /**
  38637. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38638. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38639. * 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;
  38640. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38641. */
  38642. get: function () {
  38643. return this._imageProcessingConfiguration.colorCurves;
  38644. },
  38645. /**
  38646. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38647. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38648. * 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;
  38649. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38650. */
  38651. set: function (value) {
  38652. this._imageProcessingConfiguration.colorCurves = value;
  38653. },
  38654. enumerable: true,
  38655. configurable: true
  38656. });
  38657. PBRMaterial.prototype.getClassName = function () {
  38658. return "PBRMaterial";
  38659. };
  38660. PBRMaterial.prototype.getActiveTextures = function () {
  38661. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38662. if (this._albedoTexture) {
  38663. activeTextures.push(this._albedoTexture);
  38664. }
  38665. if (this._ambientTexture) {
  38666. activeTextures.push(this._ambientTexture);
  38667. }
  38668. if (this._opacityTexture) {
  38669. activeTextures.push(this._opacityTexture);
  38670. }
  38671. if (this._reflectionTexture) {
  38672. activeTextures.push(this._reflectionTexture);
  38673. }
  38674. if (this._emissiveTexture) {
  38675. activeTextures.push(this._emissiveTexture);
  38676. }
  38677. if (this._reflectivityTexture) {
  38678. activeTextures.push(this._reflectivityTexture);
  38679. }
  38680. if (this._metallicTexture) {
  38681. activeTextures.push(this._metallicTexture);
  38682. }
  38683. if (this._microSurfaceTexture) {
  38684. activeTextures.push(this._microSurfaceTexture);
  38685. }
  38686. if (this._bumpTexture) {
  38687. activeTextures.push(this._bumpTexture);
  38688. }
  38689. if (this._lightmapTexture) {
  38690. activeTextures.push(this._lightmapTexture);
  38691. }
  38692. if (this._refractionTexture) {
  38693. activeTextures.push(this._refractionTexture);
  38694. }
  38695. return activeTextures;
  38696. };
  38697. PBRMaterial.prototype.hasTexture = function (texture) {
  38698. if (_super.prototype.hasTexture.call(this, texture)) {
  38699. return true;
  38700. }
  38701. if (this._albedoTexture === texture) {
  38702. return true;
  38703. }
  38704. if (this._ambientTexture === texture) {
  38705. return true;
  38706. }
  38707. if (this._opacityTexture === texture) {
  38708. return true;
  38709. }
  38710. if (this._reflectionTexture === texture) {
  38711. return true;
  38712. }
  38713. if (this._reflectivityTexture === texture) {
  38714. return true;
  38715. }
  38716. if (this._metallicTexture === texture) {
  38717. return true;
  38718. }
  38719. if (this._microSurfaceTexture === texture) {
  38720. return true;
  38721. }
  38722. if (this._bumpTexture === texture) {
  38723. return true;
  38724. }
  38725. if (this._lightmapTexture === texture) {
  38726. return true;
  38727. }
  38728. if (this._refractionTexture === texture) {
  38729. return true;
  38730. }
  38731. return false;
  38732. };
  38733. PBRMaterial.prototype.clone = function (name) {
  38734. var _this = this;
  38735. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  38736. };
  38737. PBRMaterial.prototype.serialize = function () {
  38738. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38739. serializationObject.customType = "BABYLON.PBRMaterial";
  38740. return serializationObject;
  38741. };
  38742. // Statics
  38743. PBRMaterial.Parse = function (source, scene, rootUrl) {
  38744. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  38745. };
  38746. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  38747. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  38748. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  38749. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  38750. __decorate([
  38751. BABYLON.serialize(),
  38752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38753. ], PBRMaterial.prototype, "directIntensity", void 0);
  38754. __decorate([
  38755. BABYLON.serialize(),
  38756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38757. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  38758. __decorate([
  38759. BABYLON.serialize(),
  38760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38761. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  38762. __decorate([
  38763. BABYLON.serialize(),
  38764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38765. ], PBRMaterial.prototype, "specularIntensity", void 0);
  38766. __decorate([
  38767. BABYLON.serialize(),
  38768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38769. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  38770. __decorate([
  38771. BABYLON.serializeAsTexture(),
  38772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38773. ], PBRMaterial.prototype, "albedoTexture", void 0);
  38774. __decorate([
  38775. BABYLON.serializeAsTexture(),
  38776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38777. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38778. __decorate([
  38779. BABYLON.serialize(),
  38780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38781. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38782. __decorate([
  38783. BABYLON.serializeAsTexture(),
  38784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38785. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38786. __decorate([
  38787. BABYLON.serializeAsTexture(),
  38788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38789. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38790. __decorate([
  38791. BABYLON.serializeAsTexture(),
  38792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38793. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38794. __decorate([
  38795. BABYLON.serializeAsTexture(),
  38796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38797. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38798. __decorate([
  38799. BABYLON.serializeAsTexture(),
  38800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38801. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38802. __decorate([
  38803. BABYLON.serialize(),
  38804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38805. ], PBRMaterial.prototype, "metallic", void 0);
  38806. __decorate([
  38807. BABYLON.serialize(),
  38808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38809. ], PBRMaterial.prototype, "roughness", void 0);
  38810. __decorate([
  38811. BABYLON.serializeAsTexture(),
  38812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38813. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38814. __decorate([
  38815. BABYLON.serializeAsTexture(),
  38816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38817. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38818. __decorate([
  38819. BABYLON.serializeAsTexture(),
  38820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38821. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38822. __decorate([
  38823. BABYLON.serializeAsTexture(),
  38824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38825. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38826. __decorate([
  38827. BABYLON.serializeAsColor3("ambient"),
  38828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38829. ], PBRMaterial.prototype, "ambientColor", void 0);
  38830. __decorate([
  38831. BABYLON.serializeAsColor3("albedo"),
  38832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38833. ], PBRMaterial.prototype, "albedoColor", void 0);
  38834. __decorate([
  38835. BABYLON.serializeAsColor3("reflectivity"),
  38836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38837. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38838. __decorate([
  38839. BABYLON.serializeAsColor3("reflection"),
  38840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38841. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38842. __decorate([
  38843. BABYLON.serializeAsColor3("emissive"),
  38844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38845. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38846. __decorate([
  38847. BABYLON.serialize(),
  38848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38849. ], PBRMaterial.prototype, "microSurface", void 0);
  38850. __decorate([
  38851. BABYLON.serialize(),
  38852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38853. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38854. __decorate([
  38855. BABYLON.serialize(),
  38856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38857. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38858. __decorate([
  38859. BABYLON.serialize(),
  38860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38861. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38862. __decorate([
  38863. BABYLON.serialize(),
  38864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38865. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38866. __decorate([
  38867. BABYLON.serialize(),
  38868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38869. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38870. __decorate([
  38871. BABYLON.serialize(),
  38872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38873. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38874. __decorate([
  38875. BABYLON.serialize(),
  38876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38877. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38878. __decorate([
  38879. BABYLON.serialize(),
  38880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38881. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38882. __decorate([
  38883. BABYLON.serialize(),
  38884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38885. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38886. __decorate([
  38887. BABYLON.serialize(),
  38888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38889. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38890. __decorate([
  38891. BABYLON.serialize(),
  38892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38893. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38894. __decorate([
  38895. BABYLON.serialize(),
  38896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38897. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38898. __decorate([
  38899. BABYLON.serialize(),
  38900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38901. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38902. __decorate([
  38903. BABYLON.serialize(),
  38904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38905. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38906. __decorate([
  38907. BABYLON.serialize(),
  38908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38909. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38910. __decorate([
  38911. BABYLON.serialize(),
  38912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38913. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38914. __decorate([
  38915. BABYLON.serialize(),
  38916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38917. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38918. __decorate([
  38919. BABYLON.serialize(),
  38920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38921. ], PBRMaterial.prototype, "useParallax", void 0);
  38922. __decorate([
  38923. BABYLON.serialize(),
  38924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38925. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38926. __decorate([
  38927. BABYLON.serialize(),
  38928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38929. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38930. __decorate([
  38931. BABYLON.serialize(),
  38932. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38933. ], PBRMaterial.prototype, "disableLighting", void 0);
  38934. __decorate([
  38935. BABYLON.serialize(),
  38936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38937. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38938. __decorate([
  38939. BABYLON.serialize(),
  38940. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38941. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38942. __decorate([
  38943. BABYLON.serialize(),
  38944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38945. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38946. __decorate([
  38947. BABYLON.serialize(),
  38948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38949. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38950. __decorate([
  38951. BABYLON.serialize(),
  38952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38953. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38954. __decorate([
  38955. BABYLON.serialize(),
  38956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38957. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  38958. __decorate([
  38959. BABYLON.serialize(),
  38960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38961. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38962. __decorate([
  38963. BABYLON.serializeAsTexture(),
  38964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38965. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38966. __decorate([
  38967. BABYLON.serialize(),
  38968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38969. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38970. return PBRMaterial;
  38971. }(BABYLON.PBRBaseMaterial));
  38972. BABYLON.PBRMaterial = PBRMaterial;
  38973. })(BABYLON || (BABYLON = {}));
  38974. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38975. var BABYLON;
  38976. (function (BABYLON) {
  38977. /**
  38978. * The PBR material of BJS following the metal roughness convention.
  38979. *
  38980. * This fits to the PBR convention in the GLTF definition:
  38981. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38982. */
  38983. var PBRMetallicRoughnessMaterial = (function (_super) {
  38984. __extends(PBRMetallicRoughnessMaterial, _super);
  38985. /**
  38986. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38987. *
  38988. * @param name The material name
  38989. * @param scene The scene the material will be use in.
  38990. */
  38991. function PBRMetallicRoughnessMaterial(name, scene) {
  38992. var _this = _super.call(this, name, scene) || this;
  38993. _this._useRoughnessFromMetallicTextureAlpha = false;
  38994. _this._useRoughnessFromMetallicTextureGreen = true;
  38995. _this._useMetallnessFromMetallicTextureBlue = true;
  38996. return _this;
  38997. }
  38998. /**
  38999. * Return the currrent class name of the material.
  39000. */
  39001. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  39002. return "PBRMetallicRoughnessMaterial";
  39003. };
  39004. /**
  39005. * Return the active textures of the material.
  39006. */
  39007. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  39008. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39009. if (this.baseTexture) {
  39010. activeTextures.push(this.baseTexture);
  39011. }
  39012. if (this.metallicRoughnessTexture) {
  39013. activeTextures.push(this.metallicRoughnessTexture);
  39014. }
  39015. return activeTextures;
  39016. };
  39017. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  39018. if (_super.prototype.hasTexture.call(this, texture)) {
  39019. return true;
  39020. }
  39021. if (this.baseTexture === texture) {
  39022. return true;
  39023. }
  39024. if (this.metallicRoughnessTexture === texture) {
  39025. return true;
  39026. }
  39027. return false;
  39028. };
  39029. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  39030. var _this = this;
  39031. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  39032. };
  39033. /**
  39034. * Serialize the material to a parsable JSON object.
  39035. */
  39036. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  39037. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39038. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  39039. return serializationObject;
  39040. };
  39041. /**
  39042. * Parses a JSON object correponding to the serialize function.
  39043. */
  39044. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  39045. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  39046. };
  39047. __decorate([
  39048. BABYLON.serializeAsColor3(),
  39049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39050. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  39051. __decorate([
  39052. BABYLON.serializeAsTexture(),
  39053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39054. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  39055. __decorate([
  39056. BABYLON.serialize(),
  39057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39058. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  39059. __decorate([
  39060. BABYLON.serialize(),
  39061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39062. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  39063. __decorate([
  39064. BABYLON.serializeAsTexture(),
  39065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  39066. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  39067. return PBRMetallicRoughnessMaterial;
  39068. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  39069. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  39070. })(BABYLON || (BABYLON = {}));
  39071. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  39072. var BABYLON;
  39073. (function (BABYLON) {
  39074. /**
  39075. * The PBR material of BJS following the specular glossiness convention.
  39076. *
  39077. * This fits to the PBR convention in the GLTF definition:
  39078. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  39079. */
  39080. var PBRSpecularGlossinessMaterial = (function (_super) {
  39081. __extends(PBRSpecularGlossinessMaterial, _super);
  39082. /**
  39083. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  39084. *
  39085. * @param name The material name
  39086. * @param scene The scene the material will be use in.
  39087. */
  39088. function PBRSpecularGlossinessMaterial(name, scene) {
  39089. var _this = _super.call(this, name, scene) || this;
  39090. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  39091. return _this;
  39092. }
  39093. /**
  39094. * Return the currrent class name of the material.
  39095. */
  39096. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  39097. return "PBRSpecularGlossinessMaterial";
  39098. };
  39099. /**
  39100. * Return the active textures of the material.
  39101. */
  39102. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  39103. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39104. if (this.diffuseTexture) {
  39105. activeTextures.push(this.diffuseTexture);
  39106. }
  39107. if (this.specularGlossinessTexture) {
  39108. activeTextures.push(this.specularGlossinessTexture);
  39109. }
  39110. return activeTextures;
  39111. };
  39112. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  39113. if (_super.prototype.hasTexture.call(this, texture)) {
  39114. return true;
  39115. }
  39116. if (this.diffuseTexture === texture) {
  39117. return true;
  39118. }
  39119. if (this.specularGlossinessTexture === texture) {
  39120. return true;
  39121. }
  39122. return false;
  39123. };
  39124. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  39125. var _this = this;
  39126. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  39127. };
  39128. /**
  39129. * Serialize the material to a parsable JSON object.
  39130. */
  39131. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  39132. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39133. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  39134. return serializationObject;
  39135. };
  39136. /**
  39137. * Parses a JSON object correponding to the serialize function.
  39138. */
  39139. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  39140. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  39141. };
  39142. __decorate([
  39143. BABYLON.serializeAsColor3("diffuse"),
  39144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39145. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  39146. __decorate([
  39147. BABYLON.serializeAsTexture(),
  39148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39149. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  39150. __decorate([
  39151. BABYLON.serializeAsColor3("specular"),
  39152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  39153. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  39154. __decorate([
  39155. BABYLON.serialize(),
  39156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  39157. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  39158. __decorate([
  39159. BABYLON.serializeAsTexture(),
  39160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  39161. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  39162. return PBRSpecularGlossinessMaterial;
  39163. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  39164. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  39165. })(BABYLON || (BABYLON = {}));
  39166. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  39167. var BABYLON;
  39168. (function (BABYLON) {
  39169. var ShaderMaterial = (function (_super) {
  39170. __extends(ShaderMaterial, _super);
  39171. function ShaderMaterial(name, scene, shaderPath, options) {
  39172. var _this = _super.call(this, name, scene) || this;
  39173. _this._textures = {};
  39174. _this._textureArrays = {};
  39175. _this._floats = {};
  39176. _this._floatsArrays = {};
  39177. _this._colors3 = {};
  39178. _this._colors3Arrays = {};
  39179. _this._colors4 = {};
  39180. _this._vectors2 = {};
  39181. _this._vectors3 = {};
  39182. _this._vectors4 = {};
  39183. _this._matrices = {};
  39184. _this._matrices3x3 = {};
  39185. _this._matrices2x2 = {};
  39186. _this._vectors3Arrays = {};
  39187. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  39188. _this._shaderPath = shaderPath;
  39189. options.needAlphaBlending = options.needAlphaBlending || false;
  39190. options.needAlphaTesting = options.needAlphaTesting || false;
  39191. options.attributes = options.attributes || ["position", "normal", "uv"];
  39192. options.uniforms = options.uniforms || ["worldViewProjection"];
  39193. options.uniformBuffers = options.uniformBuffers || [];
  39194. options.samplers = options.samplers || [];
  39195. options.defines = options.defines || [];
  39196. _this._options = options;
  39197. return _this;
  39198. }
  39199. ShaderMaterial.prototype.getClassName = function () {
  39200. return "ShaderMaterial";
  39201. };
  39202. ShaderMaterial.prototype.needAlphaBlending = function () {
  39203. return this._options.needAlphaBlending;
  39204. };
  39205. ShaderMaterial.prototype.needAlphaTesting = function () {
  39206. return this._options.needAlphaTesting;
  39207. };
  39208. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  39209. if (this._options.uniforms.indexOf(uniformName) === -1) {
  39210. this._options.uniforms.push(uniformName);
  39211. }
  39212. };
  39213. ShaderMaterial.prototype.setTexture = function (name, texture) {
  39214. if (this._options.samplers.indexOf(name) === -1) {
  39215. this._options.samplers.push(name);
  39216. }
  39217. this._textures[name] = texture;
  39218. return this;
  39219. };
  39220. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  39221. if (this._options.samplers.indexOf(name) === -1) {
  39222. this._options.samplers.push(name);
  39223. }
  39224. this._checkUniform(name);
  39225. this._textureArrays[name] = textures;
  39226. return this;
  39227. };
  39228. ShaderMaterial.prototype.setFloat = function (name, value) {
  39229. this._checkUniform(name);
  39230. this._floats[name] = value;
  39231. return this;
  39232. };
  39233. ShaderMaterial.prototype.setFloats = function (name, value) {
  39234. this._checkUniform(name);
  39235. this._floatsArrays[name] = value;
  39236. return this;
  39237. };
  39238. ShaderMaterial.prototype.setColor3 = function (name, value) {
  39239. this._checkUniform(name);
  39240. this._colors3[name] = value;
  39241. return this;
  39242. };
  39243. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  39244. this._checkUniform(name);
  39245. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  39246. color.toArray(arr, arr.length);
  39247. return arr;
  39248. }, []);
  39249. return this;
  39250. };
  39251. ShaderMaterial.prototype.setColor4 = function (name, value) {
  39252. this._checkUniform(name);
  39253. this._colors4[name] = value;
  39254. return this;
  39255. };
  39256. ShaderMaterial.prototype.setVector2 = function (name, value) {
  39257. this._checkUniform(name);
  39258. this._vectors2[name] = value;
  39259. return this;
  39260. };
  39261. ShaderMaterial.prototype.setVector3 = function (name, value) {
  39262. this._checkUniform(name);
  39263. this._vectors3[name] = value;
  39264. return this;
  39265. };
  39266. ShaderMaterial.prototype.setVector4 = function (name, value) {
  39267. this._checkUniform(name);
  39268. this._vectors4[name] = value;
  39269. return this;
  39270. };
  39271. ShaderMaterial.prototype.setMatrix = function (name, value) {
  39272. this._checkUniform(name);
  39273. this._matrices[name] = value;
  39274. return this;
  39275. };
  39276. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  39277. this._checkUniform(name);
  39278. this._matrices3x3[name] = value;
  39279. return this;
  39280. };
  39281. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  39282. this._checkUniform(name);
  39283. this._matrices2x2[name] = value;
  39284. return this;
  39285. };
  39286. ShaderMaterial.prototype.setArray3 = function (name, value) {
  39287. this._checkUniform(name);
  39288. this._vectors3Arrays[name] = value;
  39289. return this;
  39290. };
  39291. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  39292. if (!mesh) {
  39293. return true;
  39294. }
  39295. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  39296. return false;
  39297. }
  39298. return false;
  39299. };
  39300. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  39301. var scene = this.getScene();
  39302. var engine = scene.getEngine();
  39303. if (!this.checkReadyOnEveryCall) {
  39304. if (this._renderId === scene.getRenderId()) {
  39305. if (this._checkCache(scene, mesh, useInstances)) {
  39306. return true;
  39307. }
  39308. }
  39309. }
  39310. // Instances
  39311. var defines = [];
  39312. var attribs = [];
  39313. var fallbacks = new BABYLON.EffectFallbacks();
  39314. if (useInstances) {
  39315. defines.push("#define INSTANCES");
  39316. }
  39317. for (var index = 0; index < this._options.defines.length; index++) {
  39318. defines.push(this._options.defines[index]);
  39319. }
  39320. for (var index = 0; index < this._options.attributes.length; index++) {
  39321. attribs.push(this._options.attributes[index]);
  39322. }
  39323. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39324. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39325. defines.push("#define VERTEXCOLOR");
  39326. }
  39327. // Bones
  39328. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  39329. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39330. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39331. if (mesh.numBoneInfluencers > 4) {
  39332. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39333. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39334. }
  39335. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39336. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39337. fallbacks.addCPUSkinningFallback(0, mesh);
  39338. if (this._options.uniforms.indexOf("mBones") === -1) {
  39339. this._options.uniforms.push("mBones");
  39340. }
  39341. }
  39342. else {
  39343. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39344. }
  39345. // Textures
  39346. for (var name in this._textures) {
  39347. if (!this._textures[name].isReady()) {
  39348. return false;
  39349. }
  39350. }
  39351. // Alpha test
  39352. if (engine.getAlphaTesting()) {
  39353. defines.push("#define ALPHATEST");
  39354. }
  39355. var previousEffect = this._effect;
  39356. var join = defines.join("\n");
  39357. this._effect = engine.createEffect(this._shaderPath, {
  39358. attributes: attribs,
  39359. uniformsNames: this._options.uniforms,
  39360. uniformBuffersNames: this._options.uniformBuffers,
  39361. samplers: this._options.samplers,
  39362. defines: join,
  39363. fallbacks: fallbacks,
  39364. onCompiled: this.onCompiled,
  39365. onError: this.onError
  39366. }, engine);
  39367. if (!this._effect.isReady()) {
  39368. return false;
  39369. }
  39370. if (previousEffect !== this._effect) {
  39371. scene.resetCachedMaterial();
  39372. }
  39373. this._renderId = scene.getRenderId();
  39374. return true;
  39375. };
  39376. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39377. var scene = this.getScene();
  39378. if (this._options.uniforms.indexOf("world") !== -1) {
  39379. this._effect.setMatrix("world", world);
  39380. }
  39381. if (this._options.uniforms.indexOf("worldView") !== -1) {
  39382. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  39383. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  39384. }
  39385. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  39386. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  39387. }
  39388. };
  39389. ShaderMaterial.prototype.bind = function (world, mesh) {
  39390. // Std values
  39391. this.bindOnlyWorldMatrix(world);
  39392. if (this.getScene().getCachedMaterial() !== this) {
  39393. if (this._options.uniforms.indexOf("view") !== -1) {
  39394. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  39395. }
  39396. if (this._options.uniforms.indexOf("projection") !== -1) {
  39397. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  39398. }
  39399. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  39400. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  39401. }
  39402. // Bones
  39403. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  39404. var name;
  39405. // Texture
  39406. for (name in this._textures) {
  39407. this._effect.setTexture(name, this._textures[name]);
  39408. }
  39409. // Texture arrays
  39410. for (name in this._textureArrays) {
  39411. this._effect.setTextureArray(name, this._textureArrays[name]);
  39412. }
  39413. // Float
  39414. for (name in this._floats) {
  39415. this._effect.setFloat(name, this._floats[name]);
  39416. }
  39417. // Float s
  39418. for (name in this._floatsArrays) {
  39419. this._effect.setArray(name, this._floatsArrays[name]);
  39420. }
  39421. // Color3
  39422. for (name in this._colors3) {
  39423. this._effect.setColor3(name, this._colors3[name]);
  39424. }
  39425. for (name in this._colors3Arrays) {
  39426. this._effect.setArray3(name, this._colors3Arrays[name]);
  39427. }
  39428. // Color4
  39429. for (name in this._colors4) {
  39430. var color = this._colors4[name];
  39431. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  39432. }
  39433. // Vector2
  39434. for (name in this._vectors2) {
  39435. this._effect.setVector2(name, this._vectors2[name]);
  39436. }
  39437. // Vector3
  39438. for (name in this._vectors3) {
  39439. this._effect.setVector3(name, this._vectors3[name]);
  39440. }
  39441. // Vector4
  39442. for (name in this._vectors4) {
  39443. this._effect.setVector4(name, this._vectors4[name]);
  39444. }
  39445. // Matrix
  39446. for (name in this._matrices) {
  39447. this._effect.setMatrix(name, this._matrices[name]);
  39448. }
  39449. // Matrix 3x3
  39450. for (name in this._matrices3x3) {
  39451. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  39452. }
  39453. // Matrix 2x2
  39454. for (name in this._matrices2x2) {
  39455. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  39456. }
  39457. // Vector3Array
  39458. for (name in this._vectors3Arrays) {
  39459. this._effect.setArray3(name, this._vectors3Arrays[name]);
  39460. }
  39461. }
  39462. this._afterBind(mesh);
  39463. };
  39464. ShaderMaterial.prototype.getActiveTextures = function () {
  39465. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39466. for (var name in this._textures) {
  39467. activeTextures.push(this._textures[name]);
  39468. }
  39469. for (var name in this._textureArrays) {
  39470. var array = this._textureArrays[name];
  39471. for (var index = 0; index < array.length; index++) {
  39472. activeTextures.push(array[index]);
  39473. }
  39474. }
  39475. return activeTextures;
  39476. };
  39477. ShaderMaterial.prototype.hasTexture = function (texture) {
  39478. if (_super.prototype.hasTexture.call(this, texture)) {
  39479. return true;
  39480. }
  39481. for (var name in this._textures) {
  39482. if (this._textures[name] === texture) {
  39483. return true;
  39484. }
  39485. }
  39486. for (var name in this._textureArrays) {
  39487. var array = this._textureArrays[name];
  39488. for (var index = 0; index < array.length; index++) {
  39489. if (array[index] === texture) {
  39490. return true;
  39491. }
  39492. }
  39493. }
  39494. return false;
  39495. };
  39496. ShaderMaterial.prototype.clone = function (name) {
  39497. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  39498. return newShaderMaterial;
  39499. };
  39500. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39501. if (forceDisposeTextures) {
  39502. var name;
  39503. for (name in this._textures) {
  39504. this._textures[name].dispose();
  39505. }
  39506. for (name in this._textureArrays) {
  39507. var array = this._textureArrays[name];
  39508. for (var index = 0; index < array.length; index++) {
  39509. array[index].dispose();
  39510. }
  39511. }
  39512. }
  39513. this._textures = {};
  39514. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39515. };
  39516. ShaderMaterial.prototype.serialize = function () {
  39517. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39518. serializationObject.customType = "BABYLON.ShaderMaterial";
  39519. serializationObject.options = this._options;
  39520. serializationObject.shaderPath = this._shaderPath;
  39521. var name;
  39522. // Texture
  39523. serializationObject.textures = {};
  39524. for (name in this._textures) {
  39525. serializationObject.textures[name] = this._textures[name].serialize();
  39526. }
  39527. // Texture arrays
  39528. serializationObject.textureArrays = {};
  39529. for (name in this._textureArrays) {
  39530. serializationObject.textureArrays[name] = [];
  39531. var array = this._textureArrays[name];
  39532. for (var index = 0; index < array.length; index++) {
  39533. serializationObject.textureArrays[name].push(array[index].serialize());
  39534. }
  39535. }
  39536. // Float
  39537. serializationObject.floats = {};
  39538. for (name in this._floats) {
  39539. serializationObject.floats[name] = this._floats[name];
  39540. }
  39541. // Float s
  39542. serializationObject.floatArrays = {};
  39543. for (name in this._floatsArrays) {
  39544. serializationObject.floatArrays[name] = this._floatsArrays[name];
  39545. }
  39546. // Color3
  39547. serializationObject.colors3 = {};
  39548. for (name in this._colors3) {
  39549. serializationObject.colors3[name] = this._colors3[name].asArray();
  39550. }
  39551. // Color3 array
  39552. serializationObject.colors3Arrays = {};
  39553. for (name in this._colors3Arrays) {
  39554. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  39555. }
  39556. // Color4
  39557. serializationObject.colors4 = {};
  39558. for (name in this._colors4) {
  39559. serializationObject.colors4[name] = this._colors4[name].asArray();
  39560. }
  39561. // Vector2
  39562. serializationObject.vectors2 = {};
  39563. for (name in this._vectors2) {
  39564. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  39565. }
  39566. // Vector3
  39567. serializationObject.vectors3 = {};
  39568. for (name in this._vectors3) {
  39569. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  39570. }
  39571. // Vector4
  39572. serializationObject.vectors4 = {};
  39573. for (name in this._vectors4) {
  39574. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  39575. }
  39576. // Matrix
  39577. serializationObject.matrices = {};
  39578. for (name in this._matrices) {
  39579. serializationObject.matrices[name] = this._matrices[name].asArray();
  39580. }
  39581. // Matrix 3x3
  39582. serializationObject.matrices3x3 = {};
  39583. for (name in this._matrices3x3) {
  39584. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  39585. }
  39586. // Matrix 2x2
  39587. serializationObject.matrices2x2 = {};
  39588. for (name in this._matrices2x2) {
  39589. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  39590. }
  39591. // Vector3Array
  39592. serializationObject.vectors3Arrays = {};
  39593. for (name in this._vectors3Arrays) {
  39594. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  39595. }
  39596. return serializationObject;
  39597. };
  39598. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  39599. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  39600. var name;
  39601. // Texture
  39602. for (name in source.textures) {
  39603. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  39604. }
  39605. // Texture arrays
  39606. for (name in source.textureArrays) {
  39607. var array = source.textureArrays[name];
  39608. var textureArray = new Array();
  39609. for (var index = 0; index < array.length; index++) {
  39610. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  39611. }
  39612. material.setTextureArray(name, textureArray);
  39613. }
  39614. // Float
  39615. for (name in source.floats) {
  39616. material.setFloat(name, source.floats[name]);
  39617. }
  39618. // Float s
  39619. for (name in source.floatsArrays) {
  39620. material.setFloats(name, source.floatsArrays[name]);
  39621. }
  39622. // Color3
  39623. for (name in source.colors3) {
  39624. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  39625. }
  39626. // Color3 arrays
  39627. for (name in source.colors3Arrays) {
  39628. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  39629. if (i % 3 === 0) {
  39630. arr.push([num]);
  39631. }
  39632. else {
  39633. arr[arr.length - 1].push(num);
  39634. }
  39635. return arr;
  39636. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  39637. material.setColor3Array(name, colors);
  39638. }
  39639. // Color4
  39640. for (name in source.colors4) {
  39641. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  39642. }
  39643. // Vector2
  39644. for (name in source.vectors2) {
  39645. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  39646. }
  39647. // Vector3
  39648. for (name in source.vectors3) {
  39649. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  39650. }
  39651. // Vector4
  39652. for (name in source.vectors4) {
  39653. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  39654. }
  39655. // Matrix
  39656. for (name in source.matrices) {
  39657. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  39658. }
  39659. // Matrix 3x3
  39660. for (name in source.matrices3x3) {
  39661. material.setMatrix3x3(name, source.matrices3x3[name]);
  39662. }
  39663. // Matrix 2x2
  39664. for (name in source.matrices2x2) {
  39665. material.setMatrix2x2(name, source.matrices2x2[name]);
  39666. }
  39667. // Vector3Array
  39668. for (name in source.vectors3Arrays) {
  39669. material.setArray3(name, source.vectors3Arrays[name]);
  39670. }
  39671. return material;
  39672. };
  39673. return ShaderMaterial;
  39674. }(BABYLON.Material));
  39675. BABYLON.ShaderMaterial = ShaderMaterial;
  39676. })(BABYLON || (BABYLON = {}));
  39677. //# sourceMappingURL=babylon.shaderMaterial.js.map
  39678. var BABYLON;
  39679. (function (BABYLON) {
  39680. var MeshBuilder = (function () {
  39681. function MeshBuilder() {
  39682. }
  39683. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  39684. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  39685. return BABYLON.Mesh.DOUBLESIDE;
  39686. }
  39687. if (orientation === undefined || orientation === null) {
  39688. return BABYLON.Mesh.FRONTSIDE;
  39689. }
  39690. return orientation;
  39691. };
  39692. /**
  39693. * Creates a box mesh.
  39694. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  39695. * The parameter `size` sets the size (float) of each box side (default 1).
  39696. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  39697. * 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).
  39698. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  39699. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39700. * 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).
  39701. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39702. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39703. */
  39704. MeshBuilder.CreateBox = function (name, options, scene) {
  39705. var box = new BABYLON.Mesh(name, scene);
  39706. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39707. box.sideOrientation = options.sideOrientation;
  39708. var vertexData = BABYLON.VertexData.CreateBox(options);
  39709. vertexData.applyToMesh(box, options.updatable);
  39710. return box;
  39711. };
  39712. /**
  39713. * Creates a sphere mesh.
  39714. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  39715. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  39716. * 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`).
  39717. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  39718. * 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
  39719. * 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).
  39720. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39721. * 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).
  39722. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39723. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39724. */
  39725. MeshBuilder.CreateSphere = function (name, options, scene) {
  39726. var sphere = new BABYLON.Mesh(name, scene);
  39727. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39728. sphere.sideOrientation = options.sideOrientation;
  39729. var vertexData = BABYLON.VertexData.CreateSphere(options);
  39730. vertexData.applyToMesh(sphere, options.updatable);
  39731. return sphere;
  39732. };
  39733. /**
  39734. * Creates a plane polygonal mesh. By default, this is a disc.
  39735. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  39736. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  39737. * 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.
  39738. * 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
  39739. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39740. * 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).
  39741. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39742. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39743. */
  39744. MeshBuilder.CreateDisc = function (name, options, scene) {
  39745. var disc = new BABYLON.Mesh(name, scene);
  39746. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39747. disc.sideOrientation = options.sideOrientation;
  39748. var vertexData = BABYLON.VertexData.CreateDisc(options);
  39749. vertexData.applyToMesh(disc, options.updatable);
  39750. return disc;
  39751. };
  39752. /**
  39753. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  39754. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  39755. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  39756. * 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`).
  39757. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  39758. * 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.
  39759. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39760. * 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).
  39761. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39762. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39763. */
  39764. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  39765. var sphere = new BABYLON.Mesh(name, scene);
  39766. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39767. sphere.sideOrientation = options.sideOrientation;
  39768. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  39769. vertexData.applyToMesh(sphere, options.updatable);
  39770. return sphere;
  39771. };
  39772. ;
  39773. /**
  39774. * Creates a ribbon mesh.
  39775. * 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.
  39776. *
  39777. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  39778. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  39779. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  39780. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  39781. * 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.
  39782. * 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.
  39783. * 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
  39784. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39785. * 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).
  39786. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39787. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39788. * 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.
  39789. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  39790. * 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
  39791. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  39792. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  39793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39794. */
  39795. MeshBuilder.CreateRibbon = function (name, options, scene) {
  39796. var pathArray = options.pathArray;
  39797. var closeArray = options.closeArray;
  39798. var closePath = options.closePath;
  39799. var offset = options.offset;
  39800. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39801. var instance = options.instance;
  39802. var updatable = options.updatable;
  39803. if (instance) {
  39804. // positionFunction : ribbon case
  39805. // only pathArray and sideOrientation parameters are taken into account for positions update
  39806. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  39807. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  39808. var positionFunction = function (positions) {
  39809. var minlg = pathArray[0].length;
  39810. var i = 0;
  39811. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  39812. for (var si = 1; si <= ns; si++) {
  39813. for (var p = 0; p < pathArray.length; p++) {
  39814. var path = pathArray[p];
  39815. var l = path.length;
  39816. minlg = (minlg < l) ? minlg : l;
  39817. var j = 0;
  39818. while (j < minlg) {
  39819. positions[i] = path[j].x;
  39820. positions[i + 1] = path[j].y;
  39821. positions[i + 2] = path[j].z;
  39822. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  39823. BABYLON.Tmp.Vector3[0].x = path[j].x;
  39824. }
  39825. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  39826. BABYLON.Tmp.Vector3[1].x = path[j].x;
  39827. }
  39828. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  39829. BABYLON.Tmp.Vector3[0].y = path[j].y;
  39830. }
  39831. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  39832. BABYLON.Tmp.Vector3[1].y = path[j].y;
  39833. }
  39834. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  39835. BABYLON.Tmp.Vector3[0].z = path[j].z;
  39836. }
  39837. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  39838. BABYLON.Tmp.Vector3[1].z = path[j].z;
  39839. }
  39840. j++;
  39841. i += 3;
  39842. }
  39843. if (instance._closePath) {
  39844. positions[i] = path[0].x;
  39845. positions[i + 1] = path[0].y;
  39846. positions[i + 2] = path[0].z;
  39847. i += 3;
  39848. }
  39849. }
  39850. }
  39851. };
  39852. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39853. positionFunction(positions);
  39854. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  39855. instance._boundingInfo.update(instance._worldMatrix);
  39856. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  39857. if (options.colors) {
  39858. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39859. for (var c = 0; c < options.colors.length; c++) {
  39860. colors[c * 4] = options.colors[c].r;
  39861. colors[c * 4 + 1] = options.colors[c].g;
  39862. colors[c * 4 + 2] = options.colors[c].b;
  39863. colors[c * 4 + 3] = options.colors[c].a;
  39864. }
  39865. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  39866. }
  39867. if (options.uvs) {
  39868. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39869. for (var i = 0; i < options.uvs.length; i++) {
  39870. uvs[i * 2] = options.uvs[i].x;
  39871. uvs[i * 2 + 1] = options.uvs[i].y;
  39872. }
  39873. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  39874. }
  39875. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  39876. var indices = instance.getIndices();
  39877. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39878. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  39879. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  39880. if (instance._closePath) {
  39881. var indexFirst = 0;
  39882. var indexLast = 0;
  39883. for (var p = 0; p < pathArray.length; p++) {
  39884. indexFirst = instance._idx[p] * 3;
  39885. if (p + 1 < pathArray.length) {
  39886. indexLast = (instance._idx[p + 1] - 1) * 3;
  39887. }
  39888. else {
  39889. indexLast = normals.length - 3;
  39890. }
  39891. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  39892. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  39893. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  39894. normals[indexLast] = normals[indexFirst];
  39895. normals[indexLast + 1] = normals[indexFirst + 1];
  39896. normals[indexLast + 2] = normals[indexFirst + 2];
  39897. }
  39898. }
  39899. if (!(instance.areNormalsFrozen)) {
  39900. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  39901. }
  39902. }
  39903. return instance;
  39904. }
  39905. else {
  39906. var ribbon = new BABYLON.Mesh(name, scene);
  39907. ribbon.sideOrientation = sideOrientation;
  39908. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  39909. if (closePath) {
  39910. ribbon._idx = vertexData._idx;
  39911. }
  39912. ribbon._closePath = closePath;
  39913. ribbon._closeArray = closeArray;
  39914. vertexData.applyToMesh(ribbon, updatable);
  39915. return ribbon;
  39916. }
  39917. };
  39918. /**
  39919. * Creates a cylinder or a cone mesh.
  39920. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  39921. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  39922. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  39923. * 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.
  39924. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  39925. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  39926. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  39927. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  39928. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  39929. * 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).
  39930. * 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
  39931. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  39932. * 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
  39933. * 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.
  39934. * If `enclose` is false, a ring surface is one element.
  39935. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  39936. * 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
  39937. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39938. * 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).
  39939. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39940. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39941. */
  39942. MeshBuilder.CreateCylinder = function (name, options, scene) {
  39943. var cylinder = new BABYLON.Mesh(name, scene);
  39944. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39945. cylinder.sideOrientation = options.sideOrientation;
  39946. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  39947. vertexData.applyToMesh(cylinder, options.updatable);
  39948. return cylinder;
  39949. };
  39950. /**
  39951. * Creates a torus mesh.
  39952. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  39953. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  39954. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  39955. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  39956. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39957. * 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).
  39958. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39959. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39960. */
  39961. MeshBuilder.CreateTorus = function (name, options, scene) {
  39962. var torus = new BABYLON.Mesh(name, scene);
  39963. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39964. torus.sideOrientation = options.sideOrientation;
  39965. var vertexData = BABYLON.VertexData.CreateTorus(options);
  39966. vertexData.applyToMesh(torus, options.updatable);
  39967. return torus;
  39968. };
  39969. /**
  39970. * Creates a torus knot mesh.
  39971. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  39972. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  39973. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  39974. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  39975. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  39976. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39977. * 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).
  39978. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39979. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39980. */
  39981. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  39982. var torusKnot = new BABYLON.Mesh(name, scene);
  39983. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39984. torusKnot.sideOrientation = options.sideOrientation;
  39985. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  39986. vertexData.applyToMesh(torusKnot, options.updatable);
  39987. return torusKnot;
  39988. };
  39989. /**
  39990. * Creates a line system mesh.
  39991. * A line system is a pool of many lines gathered in a single mesh.
  39992. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  39993. * 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.
  39994. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  39995. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  39996. * 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
  39997. * 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
  39998. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  39999. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40000. */
  40001. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  40002. var instance = options.instance;
  40003. var lines = options.lines;
  40004. if (instance) {
  40005. var positionFunction = function (positions) {
  40006. var i = 0;
  40007. for (var l = 0; l < lines.length; l++) {
  40008. var points = lines[l];
  40009. for (var p = 0; p < points.length; p++) {
  40010. positions[i] = points[p].x;
  40011. positions[i + 1] = points[p].y;
  40012. positions[i + 2] = points[p].z;
  40013. i += 3;
  40014. }
  40015. }
  40016. };
  40017. instance.updateMeshPositions(positionFunction, false);
  40018. return instance;
  40019. }
  40020. // line system creation
  40021. var lineSystem = new BABYLON.LinesMesh(name, scene);
  40022. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  40023. vertexData.applyToMesh(lineSystem, options.updatable);
  40024. return lineSystem;
  40025. };
  40026. /**
  40027. * Creates a line mesh.
  40028. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  40029. * 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.
  40030. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  40031. * The parameter `points` is an array successive Vector3.
  40032. * 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
  40033. * When updating an instance, remember that only point positions can change, not the number of points.
  40034. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40035. */
  40036. MeshBuilder.CreateLines = function (name, options, scene) {
  40037. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  40038. return lines;
  40039. };
  40040. /**
  40041. * Creates a dashed line mesh.
  40042. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  40043. * 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.
  40044. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  40045. * The parameter `points` is an array successive Vector3.
  40046. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  40047. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  40048. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  40049. * 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
  40050. * When updating an instance, remember that only point positions can change, not the number of points.
  40051. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40052. */
  40053. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  40054. var points = options.points;
  40055. var instance = options.instance;
  40056. var gapSize = options.gapSize;
  40057. var dashNb = options.dashNb;
  40058. var dashSize = options.dashSize;
  40059. if (instance) {
  40060. var positionFunction = function (positions) {
  40061. var curvect = BABYLON.Vector3.Zero();
  40062. var nbSeg = positions.length / 6;
  40063. var lg = 0;
  40064. var nb = 0;
  40065. var shft = 0;
  40066. var dashshft = 0;
  40067. var curshft = 0;
  40068. var p = 0;
  40069. var i = 0;
  40070. var j = 0;
  40071. for (i = 0; i < points.length - 1; i++) {
  40072. points[i + 1].subtractToRef(points[i], curvect);
  40073. lg += curvect.length();
  40074. }
  40075. shft = lg / nbSeg;
  40076. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  40077. for (i = 0; i < points.length - 1; i++) {
  40078. points[i + 1].subtractToRef(points[i], curvect);
  40079. nb = Math.floor(curvect.length() / shft);
  40080. curvect.normalize();
  40081. j = 0;
  40082. while (j < nb && p < positions.length) {
  40083. curshft = shft * j;
  40084. positions[p] = points[i].x + curshft * curvect.x;
  40085. positions[p + 1] = points[i].y + curshft * curvect.y;
  40086. positions[p + 2] = points[i].z + curshft * curvect.z;
  40087. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  40088. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  40089. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  40090. p += 6;
  40091. j++;
  40092. }
  40093. }
  40094. while (p < positions.length) {
  40095. positions[p] = points[i].x;
  40096. positions[p + 1] = points[i].y;
  40097. positions[p + 2] = points[i].z;
  40098. p += 3;
  40099. }
  40100. };
  40101. instance.updateMeshPositions(positionFunction, false);
  40102. return instance;
  40103. }
  40104. // dashed lines creation
  40105. var dashedLines = new BABYLON.LinesMesh(name, scene);
  40106. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  40107. vertexData.applyToMesh(dashedLines, options.updatable);
  40108. dashedLines.dashSize = dashSize;
  40109. dashedLines.gapSize = gapSize;
  40110. return dashedLines;
  40111. };
  40112. /**
  40113. * Creates an extruded shape mesh.
  40114. * 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.
  40115. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  40116. *
  40117. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40118. * 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
  40119. * extruded along the Z axis.
  40120. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40121. * 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.
  40122. * The parameter `scale` (float, default 1) is the value to scale the shape.
  40123. * 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
  40124. * 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
  40125. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40126. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40127. * 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).
  40128. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40129. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40130. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40131. */
  40132. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  40133. var path = options.path;
  40134. var shape = options.shape;
  40135. var scale = options.scale || 1;
  40136. var rotation = options.rotation || 0;
  40137. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40138. var updatable = options.updatable;
  40139. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40140. var instance = options.instance;
  40141. var invertUV = options.invertUV || false;
  40142. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40143. };
  40144. /**
  40145. * Creates an custom extruded shape mesh.
  40146. * 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.
  40147. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  40148. *
  40149. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40150. * 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
  40151. * extruded along the Z axis.
  40152. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40153. * 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
  40154. * and the distance of this point from the begining of the path :
  40155. * ```javascript
  40156. * var rotationFunction = function(i, distance) {
  40157. * // do things
  40158. * return rotationValue; }
  40159. * ```
  40160. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  40161. * 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
  40162. * and the distance of this point from the begining of the path :
  40163. * ```javascript
  40164. * var scaleFunction = function(i, distance) {
  40165. * // do things
  40166. * return scaleValue;}
  40167. * ```
  40168. * It must returns a float value that will be the scale value applied to the shape on each path point.
  40169. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  40170. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  40171. * 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
  40172. * 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
  40173. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40174. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40175. * 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).
  40176. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40177. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40178. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40179. */
  40180. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  40181. var path = options.path;
  40182. var shape = options.shape;
  40183. var scaleFunction = options.scaleFunction || (function () { return 1; });
  40184. var rotationFunction = options.rotationFunction || (function () { return 0; });
  40185. var ribbonCloseArray = options.ribbonCloseArray || false;
  40186. var ribbonClosePath = options.ribbonClosePath || false;
  40187. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40188. var updatable = options.updatable;
  40189. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40190. var instance = options.instance;
  40191. var invertUV = options.invertUV || false;
  40192. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40193. };
  40194. /**
  40195. * Creates lathe mesh.
  40196. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  40197. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  40198. *
  40199. * 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
  40200. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  40201. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  40202. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  40203. * 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.
  40204. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  40205. * 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
  40206. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40207. * 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).
  40208. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40209. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40210. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40211. */
  40212. MeshBuilder.CreateLathe = function (name, options, scene) {
  40213. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  40214. var closed = (options.closed === undefined) ? true : options.closed;
  40215. var shape = options.shape;
  40216. var radius = options.radius || 1;
  40217. var tessellation = options.tessellation || 64;
  40218. var updatable = options.updatable;
  40219. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40220. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40221. var pi2 = Math.PI * 2;
  40222. var paths = new Array();
  40223. var invertUV = options.invertUV || false;
  40224. var i = 0;
  40225. var p = 0;
  40226. var step = pi2 / tessellation * arc;
  40227. var rotated;
  40228. var path = new Array();
  40229. ;
  40230. for (i = 0; i <= tessellation; i++) {
  40231. var path = [];
  40232. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  40233. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  40234. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  40235. }
  40236. for (p = 0; p < shape.length; p++) {
  40237. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  40238. path.push(rotated);
  40239. }
  40240. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  40241. 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));
  40242. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  40243. }
  40244. paths.push(path);
  40245. }
  40246. // lathe ribbon
  40247. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40248. return lathe;
  40249. };
  40250. /**
  40251. * Creates a plane mesh.
  40252. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40253. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  40254. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  40255. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  40256. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40257. * 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).
  40258. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40259. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40260. */
  40261. MeshBuilder.CreatePlane = function (name, options, scene) {
  40262. var plane = new BABYLON.Mesh(name, scene);
  40263. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40264. plane.sideOrientation = options.sideOrientation;
  40265. var vertexData = BABYLON.VertexData.CreatePlane(options);
  40266. vertexData.applyToMesh(plane, options.updatable);
  40267. if (options.sourcePlane) {
  40268. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  40269. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  40270. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  40271. plane.rotate(vectorProduct, product);
  40272. }
  40273. return plane;
  40274. };
  40275. /**
  40276. * Creates a ground mesh.
  40277. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40278. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  40279. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  40280. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40281. */
  40282. MeshBuilder.CreateGround = function (name, options, scene) {
  40283. var ground = new BABYLON.GroundMesh(name, scene);
  40284. ground._setReady(false);
  40285. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  40286. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  40287. ground._width = options.width || 1;
  40288. ground._height = options.height || 1;
  40289. ground._maxX = ground._width / 2;
  40290. ground._maxZ = ground._height / 2;
  40291. ground._minX = -ground._maxX;
  40292. ground._minZ = -ground._maxZ;
  40293. var vertexData = BABYLON.VertexData.CreateGround(options);
  40294. vertexData.applyToMesh(ground, options.updatable);
  40295. ground._setReady(true);
  40296. return ground;
  40297. };
  40298. /**
  40299. * Creates a tiled ground mesh.
  40300. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  40301. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  40302. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  40303. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  40304. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  40305. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  40306. * numbers of subdivisions on the ground width and height of each tile.
  40307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40308. */
  40309. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  40310. var tiledGround = new BABYLON.Mesh(name, scene);
  40311. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  40312. vertexData.applyToMesh(tiledGround, options.updatable);
  40313. return tiledGround;
  40314. };
  40315. /**
  40316. * Creates a ground mesh from a height map.
  40317. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  40318. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  40319. * The parameter `url` sets the URL of the height map image resource.
  40320. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  40321. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  40322. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  40323. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  40324. * 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.
  40325. * 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).
  40326. * This function is passed the newly built mesh :
  40327. * ```javascript
  40328. * function(mesh) { // do things
  40329. * return; }
  40330. * ```
  40331. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40332. */
  40333. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  40334. var width = options.width || 10.0;
  40335. var height = options.height || 10.0;
  40336. var subdivisions = options.subdivisions || 1 | 0;
  40337. var minHeight = options.minHeight || 0.0;
  40338. var maxHeight = options.maxHeight || 10.0;
  40339. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  40340. var updatable = options.updatable;
  40341. var onReady = options.onReady;
  40342. var ground = new BABYLON.GroundMesh(name, scene);
  40343. ground._subdivisionsX = subdivisions;
  40344. ground._subdivisionsY = subdivisions;
  40345. ground._width = width;
  40346. ground._height = height;
  40347. ground._maxX = ground._width / 2.0;
  40348. ground._maxZ = ground._height / 2.0;
  40349. ground._minX = -ground._maxX;
  40350. ground._minZ = -ground._maxZ;
  40351. ground._setReady(false);
  40352. var onload = function (img) {
  40353. // Getting height map data
  40354. var canvas = document.createElement("canvas");
  40355. var context = canvas.getContext("2d");
  40356. var bufferWidth = img.width;
  40357. var bufferHeight = img.height;
  40358. canvas.width = bufferWidth;
  40359. canvas.height = bufferHeight;
  40360. context.drawImage(img, 0, 0);
  40361. // Create VertexData from map data
  40362. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  40363. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  40364. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  40365. width: width, height: height,
  40366. subdivisions: subdivisions,
  40367. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  40368. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  40369. });
  40370. vertexData.applyToMesh(ground, updatable);
  40371. ground._setReady(true);
  40372. //execute ready callback, if set
  40373. if (onReady) {
  40374. onReady(ground);
  40375. }
  40376. };
  40377. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  40378. return ground;
  40379. };
  40380. /**
  40381. * Creates a polygon mesh.
  40382. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  40383. * 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.
  40384. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40385. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40386. * 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).
  40387. * Remember you can only change the shape positions, not their number when updating a polygon.
  40388. */
  40389. MeshBuilder.CreatePolygon = function (name, options, scene) {
  40390. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40391. var shape = options.shape;
  40392. var holes = options.holes || [];
  40393. var depth = options.depth || 0;
  40394. var contours = [];
  40395. var hole = [];
  40396. for (var i = 0; i < shape.length; i++) {
  40397. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  40398. }
  40399. var epsilon = 0.00000001;
  40400. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  40401. contours.pop();
  40402. }
  40403. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  40404. for (var hNb = 0; hNb < holes.length; hNb++) {
  40405. hole = [];
  40406. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  40407. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  40408. }
  40409. polygonTriangulation.addHole(hole);
  40410. }
  40411. var polygon = polygonTriangulation.build(options.updatable, depth);
  40412. polygon.sideOrientation = options.sideOrientation;
  40413. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  40414. vertexData.applyToMesh(polygon, options.updatable);
  40415. return polygon;
  40416. };
  40417. ;
  40418. /**
  40419. * Creates an extruded polygon mesh, with depth in the Y direction.
  40420. * 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).
  40421. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  40422. */
  40423. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  40424. return MeshBuilder.CreatePolygon(name, options, scene);
  40425. };
  40426. ;
  40427. /**
  40428. * Creates a tube mesh.
  40429. * 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.
  40430. *
  40431. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  40432. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  40433. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  40434. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  40435. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  40436. * 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.
  40437. * It must return a radius value (positive float) :
  40438. * ```javascript
  40439. * var radiusFunction = function(i, distance) {
  40440. * // do things
  40441. * return radius; }
  40442. * ```
  40443. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  40444. * 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
  40445. * 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
  40446. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40447. * 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).
  40448. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40449. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40450. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40451. */
  40452. MeshBuilder.CreateTube = function (name, options, scene) {
  40453. var path = options.path;
  40454. var radius = options.radius || 1.0;
  40455. var tessellation = options.tessellation || 64 | 0;
  40456. var radiusFunction = options.radiusFunction;
  40457. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40458. var invertUV = options.invertUV || false;
  40459. var updatable = options.updatable;
  40460. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40461. var instance = options.instance;
  40462. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  40463. // tube geometry
  40464. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  40465. var tangents = path3D.getTangents();
  40466. var normals = path3D.getNormals();
  40467. var distances = path3D.getDistances();
  40468. var pi2 = Math.PI * 2;
  40469. var step = pi2 / tessellation * arc;
  40470. var returnRadius = function () { return radius; };
  40471. var radiusFunctionFinal = radiusFunction || returnRadius;
  40472. var circlePath;
  40473. var rad;
  40474. var normal;
  40475. var rotated;
  40476. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  40477. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  40478. for (var i = 0; i < path.length; i++) {
  40479. rad = radiusFunctionFinal(i, distances[i]); // current radius
  40480. circlePath = Array(); // current circle array
  40481. normal = normals[i]; // current normal
  40482. for (var t = 0; t < tessellation; t++) {
  40483. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  40484. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  40485. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  40486. rotated.scaleInPlace(rad).addInPlace(path[i]);
  40487. circlePath[t] = rotated;
  40488. }
  40489. circlePaths[index] = circlePath;
  40490. index++;
  40491. }
  40492. // cap
  40493. var capPath = function (nbPoints, pathIndex) {
  40494. var pointCap = Array();
  40495. for (var i = 0; i < nbPoints; i++) {
  40496. pointCap.push(path[pathIndex]);
  40497. }
  40498. return pointCap;
  40499. };
  40500. switch (cap) {
  40501. case BABYLON.Mesh.NO_CAP:
  40502. break;
  40503. case BABYLON.Mesh.CAP_START:
  40504. circlePaths[0] = capPath(tessellation, 0);
  40505. circlePaths[1] = circlePaths[2].slice(0);
  40506. break;
  40507. case BABYLON.Mesh.CAP_END:
  40508. circlePaths[index] = circlePaths[index - 1].slice(0);
  40509. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  40510. break;
  40511. case BABYLON.Mesh.CAP_ALL:
  40512. circlePaths[0] = capPath(tessellation, 0);
  40513. circlePaths[1] = circlePaths[2].slice(0);
  40514. circlePaths[index] = circlePaths[index - 1].slice(0);
  40515. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  40516. break;
  40517. default:
  40518. break;
  40519. }
  40520. return circlePaths;
  40521. };
  40522. var path3D;
  40523. var pathArray;
  40524. if (instance) {
  40525. var arc = options.arc || instance.arc;
  40526. path3D = (instance.path3D).update(path);
  40527. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  40528. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  40529. instance.path3D = path3D;
  40530. instance.pathArray = pathArray;
  40531. instance.arc = arc;
  40532. return instance;
  40533. }
  40534. // tube creation
  40535. path3D = new BABYLON.Path3D(path);
  40536. var newPathArray = new Array();
  40537. cap = (cap < 0 || cap > 3) ? 0 : cap;
  40538. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  40539. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40540. tube.pathArray = pathArray;
  40541. tube.path3D = path3D;
  40542. tube.tessellation = tessellation;
  40543. tube.cap = cap;
  40544. tube.arc = options.arc;
  40545. return tube;
  40546. };
  40547. /**
  40548. * Creates a polyhedron mesh.
  40549. *
  40550. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  40551. * 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
  40552. * to choose the wanted type.
  40553. * The parameter `size` (positive float, default 1) sets the polygon size.
  40554. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  40555. * 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`.
  40556. * 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
  40557. * 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)`).
  40558. * 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
  40559. * 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.
  40560. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40561. * 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).
  40562. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40563. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40564. */
  40565. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  40566. var polyhedron = new BABYLON.Mesh(name, scene);
  40567. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40568. polyhedron.sideOrientation = options.sideOrientation;
  40569. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  40570. vertexData.applyToMesh(polyhedron, options.updatable);
  40571. return polyhedron;
  40572. };
  40573. /**
  40574. * Creates a decal mesh.
  40575. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  40576. * 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.
  40577. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  40578. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  40579. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  40580. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  40581. */
  40582. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  40583. var indices = sourceMesh.getIndices();
  40584. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40585. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40586. var position = options.position || BABYLON.Vector3.Zero();
  40587. var normal = options.normal || BABYLON.Vector3.Up();
  40588. var size = options.size || BABYLON.Vector3.One();
  40589. var angle = options.angle || 0;
  40590. // Getting correct rotation
  40591. if (!normal) {
  40592. var target = new BABYLON.Vector3(0, 0, 1);
  40593. var camera = sourceMesh.getScene().activeCamera;
  40594. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  40595. normal = camera.globalPosition.subtract(cameraWorldTarget);
  40596. }
  40597. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  40598. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  40599. var pitch = Math.atan2(normal.y, len);
  40600. // Matrix
  40601. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  40602. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  40603. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  40604. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  40605. var vertexData = new BABYLON.VertexData();
  40606. vertexData.indices = [];
  40607. vertexData.positions = [];
  40608. vertexData.normals = [];
  40609. vertexData.uvs = [];
  40610. var currentVertexDataIndex = 0;
  40611. var extractDecalVector3 = function (indexId) {
  40612. var vertexId = indices[indexId];
  40613. var result = new BABYLON.PositionNormalVertex();
  40614. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  40615. // Send vector to decal local world
  40616. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  40617. // Get normal
  40618. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  40619. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  40620. return result;
  40621. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  40622. var clip = function (vertices, axis) {
  40623. if (vertices.length === 0) {
  40624. return vertices;
  40625. }
  40626. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  40627. var clipVertices = function (v0, v1) {
  40628. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  40629. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  40630. };
  40631. var result = new Array();
  40632. for (var index = 0; index < vertices.length; index += 3) {
  40633. var v1Out;
  40634. var v2Out;
  40635. var v3Out;
  40636. var total = 0;
  40637. var nV1, nV2, nV3, nV4;
  40638. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  40639. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  40640. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  40641. v1Out = d1 > 0;
  40642. v2Out = d2 > 0;
  40643. v3Out = d3 > 0;
  40644. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  40645. switch (total) {
  40646. case 0:
  40647. result.push(vertices[index]);
  40648. result.push(vertices[index + 1]);
  40649. result.push(vertices[index + 2]);
  40650. break;
  40651. case 1:
  40652. if (v1Out) {
  40653. nV1 = vertices[index + 1];
  40654. nV2 = vertices[index + 2];
  40655. nV3 = clipVertices(vertices[index], nV1);
  40656. nV4 = clipVertices(vertices[index], nV2);
  40657. }
  40658. if (v2Out) {
  40659. nV1 = vertices[index];
  40660. nV2 = vertices[index + 2];
  40661. nV3 = clipVertices(vertices[index + 1], nV1);
  40662. nV4 = clipVertices(vertices[index + 1], nV2);
  40663. result.push(nV3);
  40664. result.push(nV2.clone());
  40665. result.push(nV1.clone());
  40666. result.push(nV2.clone());
  40667. result.push(nV3.clone());
  40668. result.push(nV4);
  40669. break;
  40670. }
  40671. if (v3Out) {
  40672. nV1 = vertices[index];
  40673. nV2 = vertices[index + 1];
  40674. nV3 = clipVertices(vertices[index + 2], nV1);
  40675. nV4 = clipVertices(vertices[index + 2], nV2);
  40676. }
  40677. result.push(nV1.clone());
  40678. result.push(nV2.clone());
  40679. result.push(nV3);
  40680. result.push(nV4);
  40681. result.push(nV3.clone());
  40682. result.push(nV2.clone());
  40683. break;
  40684. case 2:
  40685. if (!v1Out) {
  40686. nV1 = vertices[index].clone();
  40687. nV2 = clipVertices(nV1, vertices[index + 1]);
  40688. nV3 = clipVertices(nV1, vertices[index + 2]);
  40689. result.push(nV1);
  40690. result.push(nV2);
  40691. result.push(nV3);
  40692. }
  40693. if (!v2Out) {
  40694. nV1 = vertices[index + 1].clone();
  40695. nV2 = clipVertices(nV1, vertices[index + 2]);
  40696. nV3 = clipVertices(nV1, vertices[index]);
  40697. result.push(nV1);
  40698. result.push(nV2);
  40699. result.push(nV3);
  40700. }
  40701. if (!v3Out) {
  40702. nV1 = vertices[index + 2].clone();
  40703. nV2 = clipVertices(nV1, vertices[index]);
  40704. nV3 = clipVertices(nV1, vertices[index + 1]);
  40705. result.push(nV1);
  40706. result.push(nV2);
  40707. result.push(nV3);
  40708. }
  40709. break;
  40710. case 3:
  40711. break;
  40712. }
  40713. }
  40714. return result;
  40715. };
  40716. for (var index = 0; index < indices.length; index += 3) {
  40717. var faceVertices = new Array();
  40718. faceVertices.push(extractDecalVector3(index));
  40719. faceVertices.push(extractDecalVector3(index + 1));
  40720. faceVertices.push(extractDecalVector3(index + 2));
  40721. // Clip
  40722. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  40723. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  40724. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  40725. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  40726. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  40727. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  40728. if (faceVertices.length === 0) {
  40729. continue;
  40730. }
  40731. // Add UVs and get back to world
  40732. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  40733. var vertex = faceVertices[vIndex];
  40734. //TODO check for Int32Array | Uint32Array | Uint16Array
  40735. vertexData.indices.push(currentVertexDataIndex);
  40736. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  40737. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  40738. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  40739. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  40740. currentVertexDataIndex++;
  40741. }
  40742. }
  40743. // Return mesh
  40744. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  40745. vertexData.applyToMesh(decal);
  40746. decal.position = position.clone();
  40747. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  40748. return decal;
  40749. };
  40750. // Privates
  40751. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  40752. // extrusion geometry
  40753. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  40754. var tangents = path3D.getTangents();
  40755. var normals = path3D.getNormals();
  40756. var binormals = path3D.getBinormals();
  40757. var distances = path3D.getDistances();
  40758. var angle = 0;
  40759. var returnScale = function () { return scale; };
  40760. var returnRotation = function () { return rotation; };
  40761. var rotate = custom ? rotateFunction : returnRotation;
  40762. var scl = custom ? scaleFunction : returnScale;
  40763. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  40764. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  40765. for (var i = 0; i < curve.length; i++) {
  40766. var shapePath = new Array();
  40767. var angleStep = rotate(i, distances[i]);
  40768. var scaleRatio = scl(i, distances[i]);
  40769. for (var p = 0; p < shape.length; p++) {
  40770. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  40771. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  40772. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  40773. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  40774. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  40775. shapePath[p] = rotated;
  40776. }
  40777. shapePaths[index] = shapePath;
  40778. angle += angleStep;
  40779. index++;
  40780. }
  40781. // cap
  40782. var capPath = function (shapePath) {
  40783. var pointCap = Array();
  40784. var barycenter = BABYLON.Vector3.Zero();
  40785. var i;
  40786. for (i = 0; i < shapePath.length; i++) {
  40787. barycenter.addInPlace(shapePath[i]);
  40788. }
  40789. barycenter.scaleInPlace(1.0 / shapePath.length);
  40790. for (i = 0; i < shapePath.length; i++) {
  40791. pointCap.push(barycenter);
  40792. }
  40793. return pointCap;
  40794. };
  40795. switch (cap) {
  40796. case BABYLON.Mesh.NO_CAP:
  40797. break;
  40798. case BABYLON.Mesh.CAP_START:
  40799. shapePaths[0] = capPath(shapePaths[2]);
  40800. shapePaths[1] = shapePaths[2];
  40801. break;
  40802. case BABYLON.Mesh.CAP_END:
  40803. shapePaths[index] = shapePaths[index - 1];
  40804. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  40805. break;
  40806. case BABYLON.Mesh.CAP_ALL:
  40807. shapePaths[0] = capPath(shapePaths[2]);
  40808. shapePaths[1] = shapePaths[2];
  40809. shapePaths[index] = shapePaths[index - 1];
  40810. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  40811. break;
  40812. default:
  40813. break;
  40814. }
  40815. return shapePaths;
  40816. };
  40817. var path3D;
  40818. var pathArray;
  40819. if (instance) {
  40820. path3D = (instance.path3D).update(curve);
  40821. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  40822. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  40823. return instance;
  40824. }
  40825. // extruded shape creation
  40826. path3D = new BABYLON.Path3D(curve);
  40827. var newShapePaths = new Array();
  40828. cap = (cap < 0 || cap > 3) ? 0 : cap;
  40829. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  40830. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  40831. extrudedGeneric.pathArray = pathArray;
  40832. extrudedGeneric.path3D = path3D;
  40833. extrudedGeneric.cap = cap;
  40834. return extrudedGeneric;
  40835. };
  40836. return MeshBuilder;
  40837. }());
  40838. BABYLON.MeshBuilder = MeshBuilder;
  40839. })(BABYLON || (BABYLON = {}));
  40840. //# sourceMappingURL=babylon.meshBuilder.js.map
  40841. var BABYLON;
  40842. (function (BABYLON) {
  40843. var Layer = (function () {
  40844. function Layer(name, imgUrl, scene, isBackground, color) {
  40845. this.name = name;
  40846. this.scale = new BABYLON.Vector2(1, 1);
  40847. this.offset = new BABYLON.Vector2(0, 0);
  40848. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  40849. this.layerMask = 0x0FFFFFFF;
  40850. this._vertexBuffers = {};
  40851. // Events
  40852. /**
  40853. * An event triggered when the layer is disposed.
  40854. * @type {BABYLON.Observable}
  40855. */
  40856. this.onDisposeObservable = new BABYLON.Observable();
  40857. /**
  40858. * An event triggered before rendering the scene
  40859. * @type {BABYLON.Observable}
  40860. */
  40861. this.onBeforeRenderObservable = new BABYLON.Observable();
  40862. /**
  40863. * An event triggered after rendering the scene
  40864. * @type {BABYLON.Observable}
  40865. */
  40866. this.onAfterRenderObservable = new BABYLON.Observable();
  40867. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  40868. this.isBackground = isBackground === undefined ? true : isBackground;
  40869. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  40870. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40871. this._scene.layers.push(this);
  40872. var engine = this._scene.getEngine();
  40873. // VBO
  40874. var vertices = [];
  40875. vertices.push(1, 1);
  40876. vertices.push(-1, 1);
  40877. vertices.push(-1, -1);
  40878. vertices.push(1, -1);
  40879. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40880. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  40881. this._createIndexBuffer();
  40882. // Effects
  40883. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  40884. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  40885. }
  40886. Object.defineProperty(Layer.prototype, "onDispose", {
  40887. set: function (callback) {
  40888. if (this._onDisposeObserver) {
  40889. this.onDisposeObservable.remove(this._onDisposeObserver);
  40890. }
  40891. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  40892. },
  40893. enumerable: true,
  40894. configurable: true
  40895. });
  40896. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  40897. set: function (callback) {
  40898. if (this._onBeforeRenderObserver) {
  40899. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40900. }
  40901. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40902. },
  40903. enumerable: true,
  40904. configurable: true
  40905. });
  40906. Object.defineProperty(Layer.prototype, "onAfterRender", {
  40907. set: function (callback) {
  40908. if (this._onAfterRenderObserver) {
  40909. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40910. }
  40911. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40912. },
  40913. enumerable: true,
  40914. configurable: true
  40915. });
  40916. Layer.prototype._createIndexBuffer = function () {
  40917. var engine = this._scene.getEngine();
  40918. // Indices
  40919. var indices = [];
  40920. indices.push(0);
  40921. indices.push(1);
  40922. indices.push(2);
  40923. indices.push(0);
  40924. indices.push(2);
  40925. indices.push(3);
  40926. this._indexBuffer = engine.createIndexBuffer(indices);
  40927. };
  40928. Layer.prototype._rebuild = function () {
  40929. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  40930. this._createIndexBuffer();
  40931. };
  40932. Layer.prototype.render = function () {
  40933. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  40934. // Check
  40935. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  40936. return;
  40937. var engine = this._scene.getEngine();
  40938. this.onBeforeRenderObservable.notifyObservers(this);
  40939. // Render
  40940. engine.enableEffect(currentEffect);
  40941. engine.setState(false);
  40942. // Texture
  40943. currentEffect.setTexture("textureSampler", this.texture);
  40944. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  40945. // Color
  40946. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  40947. // Scale / offset
  40948. currentEffect.setVector2("offset", this.offset);
  40949. currentEffect.setVector2("scale", this.scale);
  40950. // VBOs
  40951. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  40952. // Draw order
  40953. if (!this.alphaTest) {
  40954. engine.setAlphaMode(this.alphaBlendingMode);
  40955. engine.draw(true, 0, 6);
  40956. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40957. }
  40958. else {
  40959. engine.draw(true, 0, 6);
  40960. }
  40961. this.onAfterRenderObservable.notifyObservers(this);
  40962. };
  40963. Layer.prototype.dispose = function () {
  40964. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40965. if (vertexBuffer) {
  40966. vertexBuffer.dispose();
  40967. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40968. }
  40969. if (this._indexBuffer) {
  40970. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40971. this._indexBuffer = null;
  40972. }
  40973. if (this.texture) {
  40974. this.texture.dispose();
  40975. this.texture = null;
  40976. }
  40977. // Remove from scene
  40978. var index = this._scene.layers.indexOf(this);
  40979. this._scene.layers.splice(index, 1);
  40980. // Callback
  40981. this.onDisposeObservable.notifyObservers(this);
  40982. this.onDisposeObservable.clear();
  40983. this.onAfterRenderObservable.clear();
  40984. this.onBeforeRenderObservable.clear();
  40985. };
  40986. return Layer;
  40987. }());
  40988. BABYLON.Layer = Layer;
  40989. })(BABYLON || (BABYLON = {}));
  40990. //# sourceMappingURL=babylon.layer.js.map
  40991. var BABYLON;
  40992. (function (BABYLON) {
  40993. var BlurPostProcess = (function (_super) {
  40994. __extends(BlurPostProcess, _super);
  40995. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  40996. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40997. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40998. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  40999. _this.direction = direction;
  41000. _this._packedFloat = false;
  41001. _this.onApplyObservable.add(function (effect) {
  41002. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  41003. });
  41004. _this.kernel = kernel;
  41005. return _this;
  41006. }
  41007. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  41008. /**
  41009. * Gets the length in pixels of the blur sample region
  41010. */
  41011. get: function () {
  41012. return this._idealKernel;
  41013. },
  41014. /**
  41015. * Sets the length in pixels of the blur sample region
  41016. */
  41017. set: function (v) {
  41018. if (this._idealKernel === v) {
  41019. return;
  41020. }
  41021. v = Math.max(v, 1);
  41022. this._idealKernel = v;
  41023. this._kernel = this._nearestBestKernel(v);
  41024. this._updateParameters();
  41025. },
  41026. enumerable: true,
  41027. configurable: true
  41028. });
  41029. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  41030. /**
  41031. * Gets wether or not the blur is unpacking/repacking floats
  41032. */
  41033. get: function () {
  41034. return this._packedFloat;
  41035. },
  41036. /**
  41037. * Sets wether or not the blur needs to unpack/repack floats
  41038. */
  41039. set: function (v) {
  41040. if (this._packedFloat === v) {
  41041. return;
  41042. }
  41043. this._packedFloat = v;
  41044. this._updateParameters();
  41045. },
  41046. enumerable: true,
  41047. configurable: true
  41048. });
  41049. BlurPostProcess.prototype._updateParameters = function () {
  41050. // Generate sampling offsets and weights
  41051. var N = this._kernel;
  41052. var centerIndex = (N - 1) / 2;
  41053. // Generate Gaussian sampling weights over kernel
  41054. var offsets = [];
  41055. var weights = [];
  41056. var totalWeight = 0;
  41057. for (var i = 0; i < N; i++) {
  41058. var u = i / (N - 1);
  41059. var w = this._gaussianWeight(u * 2.0 - 1);
  41060. offsets[i] = (i - centerIndex);
  41061. weights[i] = w;
  41062. totalWeight += w;
  41063. }
  41064. // Normalize weights
  41065. for (var i = 0; i < weights.length; i++) {
  41066. weights[i] /= totalWeight;
  41067. }
  41068. // Optimize: combine samples to take advantage of hardware linear sampling
  41069. // Walk from left to center, combining pairs (symmetrically)
  41070. var linearSamplingWeights = [];
  41071. var linearSamplingOffsets = [];
  41072. var linearSamplingMap = [];
  41073. for (var i = 0; i <= centerIndex; i += 2) {
  41074. var j = Math.min(i + 1, Math.floor(centerIndex));
  41075. var singleCenterSample = i === j;
  41076. if (singleCenterSample) {
  41077. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  41078. }
  41079. else {
  41080. var sharedCell = j === centerIndex;
  41081. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  41082. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  41083. if (offsetLinear === 0) {
  41084. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  41085. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  41086. }
  41087. else {
  41088. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  41089. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  41090. }
  41091. }
  41092. }
  41093. for (var i = 0; i < linearSamplingMap.length; i++) {
  41094. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  41095. linearSamplingWeights[i] = linearSamplingMap[i].w;
  41096. }
  41097. // Replace with optimized
  41098. offsets = linearSamplingOffsets;
  41099. weights = linearSamplingWeights;
  41100. // Generate shaders
  41101. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  41102. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  41103. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  41104. var defines = "";
  41105. for (var i = 0; i < varyingCount; i++) {
  41106. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  41107. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  41108. }
  41109. var depCount = 0;
  41110. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  41111. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  41112. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  41113. depCount++;
  41114. }
  41115. if (this.packedFloat) {
  41116. defines += "#define PACKEDFLOAT 1";
  41117. }
  41118. this.updateEffect(defines, null, null, {
  41119. varyingCount: varyingCount,
  41120. depCount: depCount
  41121. });
  41122. };
  41123. /**
  41124. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  41125. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  41126. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  41127. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  41128. * The gaps between physical kernels are compensated for in the weighting of the samples
  41129. * @param idealKernel Ideal blur kernel.
  41130. * @return Nearest best kernel.
  41131. */
  41132. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  41133. var v = Math.round(idealKernel);
  41134. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  41135. var k = _a[_i];
  41136. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  41137. return Math.max(k, 3);
  41138. }
  41139. }
  41140. return Math.max(v, 3);
  41141. };
  41142. /**
  41143. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  41144. * @param x The point on the Gaussian distribution to sample.
  41145. * @return the value of the Gaussian function at x.
  41146. */
  41147. BlurPostProcess.prototype._gaussianWeight = function (x) {
  41148. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  41149. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  41150. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  41151. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  41152. // truncated at around 1.3% of peak strength.
  41153. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  41154. var sigma = (1 / 3);
  41155. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  41156. var exponent = -((x * x) / (2.0 * sigma * sigma));
  41157. var weight = (1.0 / denominator) * Math.exp(exponent);
  41158. return weight;
  41159. };
  41160. /**
  41161. * Generates a string that can be used as a floating point number in GLSL.
  41162. * @param x Value to print.
  41163. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  41164. * @return GLSL float string.
  41165. */
  41166. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  41167. if (decimalFigures === void 0) { decimalFigures = 8; }
  41168. return x.toFixed(decimalFigures).replace(/0+$/, '');
  41169. };
  41170. return BlurPostProcess;
  41171. }(BABYLON.PostProcess));
  41172. BABYLON.BlurPostProcess = BlurPostProcess;
  41173. })(BABYLON || (BABYLON = {}));
  41174. //# sourceMappingURL=babylon.blurPostProcess.js.map
  41175. var BABYLON;
  41176. (function (BABYLON) {
  41177. var FxaaPostProcess = (function (_super) {
  41178. __extends(FxaaPostProcess, _super);
  41179. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41180. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41181. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  41182. _this.onApplyObservable.add(function (effect) {
  41183. var texelSize = _this.texelSize;
  41184. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  41185. });
  41186. return _this;
  41187. }
  41188. return FxaaPostProcess;
  41189. }(BABYLON.PostProcess));
  41190. BABYLON.FxaaPostProcess = FxaaPostProcess;
  41191. })(BABYLON || (BABYLON = {}));
  41192. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  41193. var BABYLON;
  41194. (function (BABYLON) {
  41195. var HighlightsPostProcess = (function (_super) {
  41196. __extends(HighlightsPostProcess, _super);
  41197. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41198. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41199. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  41200. }
  41201. return HighlightsPostProcess;
  41202. }(BABYLON.PostProcess));
  41203. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  41204. })(BABYLON || (BABYLON = {}));
  41205. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  41206. var BABYLON;
  41207. (function (BABYLON) {
  41208. var ImageProcessingPostProcess = (function (_super) {
  41209. __extends(ImageProcessingPostProcess, _super);
  41210. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41211. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41212. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  41213. _this._fromLinearSpace = true;
  41214. /**
  41215. * Defines cache preventing GC.
  41216. */
  41217. _this._defines = {
  41218. IMAGEPROCESSING: false,
  41219. VIGNETTE: false,
  41220. VIGNETTEBLENDMODEMULTIPLY: false,
  41221. VIGNETTEBLENDMODEOPAQUE: false,
  41222. TONEMAPPING: false,
  41223. CONTRAST: false,
  41224. COLORCURVES: false,
  41225. COLORGRADING: false,
  41226. FROMLINEARSPACE: false,
  41227. SAMPLER3DGREENDEPTH: false,
  41228. SAMPLER3DBGRMAP: false,
  41229. IMAGEPROCESSINGPOSTPROCESS: false,
  41230. EXPOSURE: false,
  41231. };
  41232. // Setup the default processing configuration to the scene.
  41233. _this._attachImageProcessingConfiguration(null, true);
  41234. _this.imageProcessingConfiguration.applyByPostProcess = true;
  41235. _this.onApply = function (effect) {
  41236. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  41237. };
  41238. return _this;
  41239. }
  41240. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  41241. /**
  41242. * Gets the image processing configuration used either in this material.
  41243. */
  41244. get: function () {
  41245. return this._imageProcessingConfiguration;
  41246. },
  41247. /**
  41248. * Sets the Default image processing configuration used either in the this material.
  41249. *
  41250. * If sets to null, the scene one is in use.
  41251. */
  41252. set: function (value) {
  41253. this._attachImageProcessingConfiguration(value);
  41254. },
  41255. enumerable: true,
  41256. configurable: true
  41257. });
  41258. /**
  41259. * Attaches a new image processing configuration to the PBR Material.
  41260. * @param configuration
  41261. */
  41262. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  41263. var _this = this;
  41264. if (doNotBuild === void 0) { doNotBuild = false; }
  41265. if (configuration === this._imageProcessingConfiguration) {
  41266. return;
  41267. }
  41268. // Detaches observer.
  41269. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41270. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41271. }
  41272. // Pick the scene configuration if needed.
  41273. if (!configuration) {
  41274. var camera = this.getCamera();
  41275. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  41276. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  41277. }
  41278. else {
  41279. this._imageProcessingConfiguration = configuration;
  41280. }
  41281. // Attaches observer.
  41282. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41283. _this._updateParameters();
  41284. });
  41285. // Ensure the effect will be rebuilt.
  41286. if (!doNotBuild) {
  41287. this._updateParameters();
  41288. }
  41289. };
  41290. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  41291. /**
  41292. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  41293. */
  41294. get: function () {
  41295. return this.imageProcessingConfiguration.colorCurves;
  41296. },
  41297. /**
  41298. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  41299. */
  41300. set: function (value) {
  41301. this.imageProcessingConfiguration.colorCurves = value;
  41302. },
  41303. enumerable: true,
  41304. configurable: true
  41305. });
  41306. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  41307. /**
  41308. * Gets wether the color curves effect is enabled.
  41309. */
  41310. get: function () {
  41311. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41312. },
  41313. /**
  41314. * Sets wether the color curves effect is enabled.
  41315. */
  41316. set: function (value) {
  41317. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41318. },
  41319. enumerable: true,
  41320. configurable: true
  41321. });
  41322. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  41323. /**
  41324. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  41325. */
  41326. get: function () {
  41327. return this.imageProcessingConfiguration.colorGradingTexture;
  41328. },
  41329. /**
  41330. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  41331. */
  41332. set: function (value) {
  41333. this.imageProcessingConfiguration.colorGradingTexture = value;
  41334. },
  41335. enumerable: true,
  41336. configurable: true
  41337. });
  41338. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  41339. /**
  41340. * Gets wether the color grading effect is enabled.
  41341. */
  41342. get: function () {
  41343. return this.imageProcessingConfiguration.colorGradingEnabled;
  41344. },
  41345. /**
  41346. * Gets wether the color grading effect is enabled.
  41347. */
  41348. set: function (value) {
  41349. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41350. },
  41351. enumerable: true,
  41352. configurable: true
  41353. });
  41354. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  41355. /**
  41356. * Gets exposure used in the effect.
  41357. */
  41358. get: function () {
  41359. return this.imageProcessingConfiguration.exposure;
  41360. },
  41361. /**
  41362. * Sets exposure used in the effect.
  41363. */
  41364. set: function (value) {
  41365. this.imageProcessingConfiguration.exposure = value;
  41366. },
  41367. enumerable: true,
  41368. configurable: true
  41369. });
  41370. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  41371. /**
  41372. * Gets wether tonemapping is enabled or not.
  41373. */
  41374. get: function () {
  41375. return this._imageProcessingConfiguration.toneMappingEnabled;
  41376. },
  41377. /**
  41378. * Sets wether tonemapping is enabled or not
  41379. */
  41380. set: function (value) {
  41381. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41382. },
  41383. enumerable: true,
  41384. configurable: true
  41385. });
  41386. ;
  41387. ;
  41388. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  41389. /**
  41390. * Gets contrast used in the effect.
  41391. */
  41392. get: function () {
  41393. return this.imageProcessingConfiguration.contrast;
  41394. },
  41395. /**
  41396. * Sets contrast used in the effect.
  41397. */
  41398. set: function (value) {
  41399. this.imageProcessingConfiguration.contrast = value;
  41400. },
  41401. enumerable: true,
  41402. configurable: true
  41403. });
  41404. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  41405. /**
  41406. * Gets Vignette stretch size.
  41407. */
  41408. get: function () {
  41409. return this.imageProcessingConfiguration.vignetteStretch;
  41410. },
  41411. /**
  41412. * Sets Vignette stretch size.
  41413. */
  41414. set: function (value) {
  41415. this.imageProcessingConfiguration.vignetteStretch = value;
  41416. },
  41417. enumerable: true,
  41418. configurable: true
  41419. });
  41420. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  41421. /**
  41422. * Gets Vignette centre X Offset.
  41423. */
  41424. get: function () {
  41425. return this.imageProcessingConfiguration.vignetteCentreX;
  41426. },
  41427. /**
  41428. * Sets Vignette centre X Offset.
  41429. */
  41430. set: function (value) {
  41431. this.imageProcessingConfiguration.vignetteCentreX = value;
  41432. },
  41433. enumerable: true,
  41434. configurable: true
  41435. });
  41436. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  41437. /**
  41438. * Gets Vignette centre Y Offset.
  41439. */
  41440. get: function () {
  41441. return this.imageProcessingConfiguration.vignetteCentreY;
  41442. },
  41443. /**
  41444. * Sets Vignette centre Y Offset.
  41445. */
  41446. set: function (value) {
  41447. this.imageProcessingConfiguration.vignetteCentreY = value;
  41448. },
  41449. enumerable: true,
  41450. configurable: true
  41451. });
  41452. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  41453. /**
  41454. * Gets Vignette weight or intensity of the vignette effect.
  41455. */
  41456. get: function () {
  41457. return this.imageProcessingConfiguration.vignetteWeight;
  41458. },
  41459. /**
  41460. * Sets Vignette weight or intensity of the vignette effect.
  41461. */
  41462. set: function (value) {
  41463. this.imageProcessingConfiguration.vignetteWeight = value;
  41464. },
  41465. enumerable: true,
  41466. configurable: true
  41467. });
  41468. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  41469. /**
  41470. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41471. * if vignetteEnabled is set to true.
  41472. */
  41473. get: function () {
  41474. return this.imageProcessingConfiguration.vignetteColor;
  41475. },
  41476. /**
  41477. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41478. * if vignetteEnabled is set to true.
  41479. */
  41480. set: function (value) {
  41481. this.imageProcessingConfiguration.vignetteColor = value;
  41482. },
  41483. enumerable: true,
  41484. configurable: true
  41485. });
  41486. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  41487. /**
  41488. * Gets Camera field of view used by the Vignette effect.
  41489. */
  41490. get: function () {
  41491. return this.imageProcessingConfiguration.vignetteCameraFov;
  41492. },
  41493. /**
  41494. * Sets Camera field of view used by the Vignette effect.
  41495. */
  41496. set: function (value) {
  41497. this.imageProcessingConfiguration.vignetteCameraFov = value;
  41498. },
  41499. enumerable: true,
  41500. configurable: true
  41501. });
  41502. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  41503. /**
  41504. * Gets the vignette blend mode allowing different kind of effect.
  41505. */
  41506. get: function () {
  41507. return this.imageProcessingConfiguration.vignetteBlendMode;
  41508. },
  41509. /**
  41510. * Sets the vignette blend mode allowing different kind of effect.
  41511. */
  41512. set: function (value) {
  41513. this.imageProcessingConfiguration.vignetteBlendMode = value;
  41514. },
  41515. enumerable: true,
  41516. configurable: true
  41517. });
  41518. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  41519. /**
  41520. * Gets wether the vignette effect is enabled.
  41521. */
  41522. get: function () {
  41523. return this.imageProcessingConfiguration.vignetteEnabled;
  41524. },
  41525. /**
  41526. * Sets wether the vignette effect is enabled.
  41527. */
  41528. set: function (value) {
  41529. this.imageProcessingConfiguration.vignetteEnabled = value;
  41530. },
  41531. enumerable: true,
  41532. configurable: true
  41533. });
  41534. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  41535. /**
  41536. * Gets wether the input of the processing is in Gamma or Linear Space.
  41537. */
  41538. get: function () {
  41539. return this._fromLinearSpace;
  41540. },
  41541. /**
  41542. * Sets wether the input of the processing is in Gamma or Linear Space.
  41543. */
  41544. set: function (value) {
  41545. if (this._fromLinearSpace === value) {
  41546. return;
  41547. }
  41548. this._fromLinearSpace = value;
  41549. this._updateParameters();
  41550. },
  41551. enumerable: true,
  41552. configurable: true
  41553. });
  41554. ImageProcessingPostProcess.prototype.getClassName = function () {
  41555. return "ImageProcessingPostProcess";
  41556. };
  41557. ImageProcessingPostProcess.prototype._updateParameters = function () {
  41558. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  41559. this.imageProcessingConfiguration.prepareDefines(this._defines);
  41560. var defines = "";
  41561. for (var define in this._defines) {
  41562. if (this._defines[define]) {
  41563. defines += "#define " + define + ";\r\n";
  41564. }
  41565. }
  41566. var samplers = ["textureSampler"];
  41567. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  41568. var uniforms = ["scale"];
  41569. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  41570. this.updateEffect(defines, uniforms, samplers);
  41571. };
  41572. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  41573. _super.prototype.dispose.call(this, camera);
  41574. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41575. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41576. }
  41577. this.imageProcessingConfiguration.applyByPostProcess = false;
  41578. };
  41579. __decorate([
  41580. BABYLON.serialize()
  41581. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  41582. return ImageProcessingPostProcess;
  41583. }(BABYLON.PostProcess));
  41584. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  41585. })(BABYLON || (BABYLON = {}));
  41586. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  41587. var BABYLON;
  41588. (function (BABYLON) {
  41589. /**
  41590. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41591. * It can help converting any input color in a desired output one. This can then be used to create effects
  41592. * from sepia, black and white to sixties or futuristic rendering...
  41593. *
  41594. * The only supported format is currently 3dl.
  41595. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41596. */
  41597. var ColorGradingTexture = (function (_super) {
  41598. __extends(ColorGradingTexture, _super);
  41599. /**
  41600. * Instantiates a ColorGradingTexture from the following parameters.
  41601. *
  41602. * @param url The location of the color gradind data (currently only supporting 3dl)
  41603. * @param scene The scene the texture will be used in
  41604. */
  41605. function ColorGradingTexture(url, scene) {
  41606. var _this = _super.call(this, scene) || this;
  41607. if (!url) {
  41608. return _this;
  41609. }
  41610. _this._textureMatrix = BABYLON.Matrix.Identity();
  41611. _this.name = url;
  41612. _this.url = url;
  41613. _this.hasAlpha = false;
  41614. _this.isCube = false;
  41615. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41616. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41617. _this.anisotropicFilteringLevel = 1;
  41618. _this._texture = _this._getFromCache(url, true);
  41619. if (!_this._texture) {
  41620. if (!scene.useDelayedTextureLoading) {
  41621. _this.loadTexture();
  41622. }
  41623. else {
  41624. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41625. }
  41626. }
  41627. return _this;
  41628. }
  41629. /**
  41630. * Returns the texture matrix used in most of the material.
  41631. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41632. */
  41633. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41634. return this._textureMatrix;
  41635. };
  41636. /**
  41637. * Occurs when the file being loaded is a .3dl LUT file.
  41638. */
  41639. ColorGradingTexture.prototype.load3dlTexture = function () {
  41640. var _this = this;
  41641. var mipLevels = 0;
  41642. var floatArrayView = null;
  41643. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41644. this._texture = texture;
  41645. var callback = function (text) {
  41646. var data;
  41647. var tempData;
  41648. var line;
  41649. var lines = text.split('\n');
  41650. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41651. var maxColor = 0;
  41652. for (var i = 0; i < lines.length; i++) {
  41653. line = lines[i];
  41654. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41655. continue;
  41656. if (line.indexOf('#') === 0)
  41657. continue;
  41658. var words = line.split(" ");
  41659. if (size === 0) {
  41660. // Number of space + one
  41661. size = words.length;
  41662. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41663. tempData = new Float32Array(size * size * size * 4);
  41664. continue;
  41665. }
  41666. if (size != 0) {
  41667. var r = Math.max(parseInt(words[0]), 0);
  41668. var g = Math.max(parseInt(words[1]), 0);
  41669. var b = Math.max(parseInt(words[2]), 0);
  41670. maxColor = Math.max(r, maxColor);
  41671. maxColor = Math.max(g, maxColor);
  41672. maxColor = Math.max(b, maxColor);
  41673. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41674. tempData[pixelStorageIndex + 0] = r;
  41675. tempData[pixelStorageIndex + 1] = g;
  41676. tempData[pixelStorageIndex + 2] = b;
  41677. pixelIndexSlice++;
  41678. if (pixelIndexSlice % size == 0) {
  41679. pixelIndexH++;
  41680. pixelIndexSlice = 0;
  41681. if (pixelIndexH % size == 0) {
  41682. pixelIndexW++;
  41683. pixelIndexH = 0;
  41684. }
  41685. }
  41686. }
  41687. }
  41688. for (var i = 0; i < tempData.length; i++) {
  41689. if (i > 0 && (i + 1) % 4 === 0) {
  41690. data[i] = 255;
  41691. }
  41692. else {
  41693. var value = tempData[i];
  41694. data[i] = (value / maxColor * 255);
  41695. }
  41696. }
  41697. texture.updateSize(size * size, size);
  41698. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41699. };
  41700. BABYLON.Tools.LoadFile(this.url, callback);
  41701. return this._texture;
  41702. };
  41703. /**
  41704. * Starts the loading process of the texture.
  41705. */
  41706. ColorGradingTexture.prototype.loadTexture = function () {
  41707. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41708. this.load3dlTexture();
  41709. }
  41710. };
  41711. /**
  41712. * Clones the color gradind texture.
  41713. */
  41714. ColorGradingTexture.prototype.clone = function () {
  41715. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41716. // Base texture
  41717. newTexture.level = this.level;
  41718. return newTexture;
  41719. };
  41720. /**
  41721. * Called during delayed load for textures.
  41722. */
  41723. ColorGradingTexture.prototype.delayLoad = function () {
  41724. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41725. return;
  41726. }
  41727. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41728. this._texture = this._getFromCache(this.url, true);
  41729. if (!this._texture) {
  41730. this.loadTexture();
  41731. }
  41732. };
  41733. /**
  41734. * Parses a color grading texture serialized by Babylon.
  41735. * @param parsedTexture The texture information being parsedTexture
  41736. * @param scene The scene to load the texture in
  41737. * @param rootUrl The root url of the data assets to load
  41738. * @return A color gradind texture
  41739. */
  41740. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41741. var texture = null;
  41742. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41743. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  41744. texture.name = parsedTexture.name;
  41745. texture.level = parsedTexture.level;
  41746. }
  41747. return texture;
  41748. };
  41749. /**
  41750. * Serializes the LUT texture to json format.
  41751. */
  41752. ColorGradingTexture.prototype.serialize = function () {
  41753. if (!this.name) {
  41754. return null;
  41755. }
  41756. var serializationObject = {};
  41757. serializationObject.name = this.name;
  41758. serializationObject.level = this.level;
  41759. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41760. return serializationObject;
  41761. };
  41762. /**
  41763. * Empty line regex stored for GC.
  41764. */
  41765. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41766. return ColorGradingTexture;
  41767. }(BABYLON.BaseTexture));
  41768. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41769. })(BABYLON || (BABYLON = {}));
  41770. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41771. var BABYLON;
  41772. (function (BABYLON) {
  41773. /**
  41774. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41775. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41776. * 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;
  41777. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41778. */
  41779. var ColorCurves = (function () {
  41780. function ColorCurves() {
  41781. this._dirty = true;
  41782. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41783. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41784. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41785. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41786. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41787. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41788. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41789. this._globalHue = 30;
  41790. this._globalDensity = 0;
  41791. this._globalSaturation = 0;
  41792. this._globalExposure = 0;
  41793. this._highlightsHue = 30;
  41794. this._highlightsDensity = 0;
  41795. this._highlightsSaturation = 0;
  41796. this._highlightsExposure = 0;
  41797. this._midtonesHue = 30;
  41798. this._midtonesDensity = 0;
  41799. this._midtonesSaturation = 0;
  41800. this._midtonesExposure = 0;
  41801. this._shadowsHue = 30;
  41802. this._shadowsDensity = 0;
  41803. this._shadowsSaturation = 0;
  41804. this._shadowsExposure = 0;
  41805. }
  41806. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41807. /**
  41808. * Gets the global Hue value.
  41809. * 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).
  41810. */
  41811. get: function () {
  41812. return this._globalHue;
  41813. },
  41814. /**
  41815. * Sets the global Hue value.
  41816. * 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).
  41817. */
  41818. set: function (value) {
  41819. this._globalHue = value;
  41820. this._dirty = true;
  41821. },
  41822. enumerable: true,
  41823. configurable: true
  41824. });
  41825. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41826. /**
  41827. * Gets the global Density value.
  41828. * 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.
  41829. * Values less than zero provide a filter of opposite hue.
  41830. */
  41831. get: function () {
  41832. return this._globalDensity;
  41833. },
  41834. /**
  41835. * Sets the global Density value.
  41836. * 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.
  41837. * Values less than zero provide a filter of opposite hue.
  41838. */
  41839. set: function (value) {
  41840. this._globalDensity = value;
  41841. this._dirty = true;
  41842. },
  41843. enumerable: true,
  41844. configurable: true
  41845. });
  41846. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41847. /**
  41848. * Gets the global Saturation value.
  41849. * 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.
  41850. */
  41851. get: function () {
  41852. return this._globalSaturation;
  41853. },
  41854. /**
  41855. * Sets the global Saturation value.
  41856. * 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.
  41857. */
  41858. set: function (value) {
  41859. this._globalSaturation = value;
  41860. this._dirty = true;
  41861. },
  41862. enumerable: true,
  41863. configurable: true
  41864. });
  41865. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41866. /**
  41867. * Gets the highlights Hue value.
  41868. * 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).
  41869. */
  41870. get: function () {
  41871. return this._highlightsHue;
  41872. },
  41873. /**
  41874. * Sets the highlights Hue value.
  41875. * 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).
  41876. */
  41877. set: function (value) {
  41878. this._highlightsHue = value;
  41879. this._dirty = true;
  41880. },
  41881. enumerable: true,
  41882. configurable: true
  41883. });
  41884. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41885. /**
  41886. * Gets the highlights Density value.
  41887. * 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.
  41888. * Values less than zero provide a filter of opposite hue.
  41889. */
  41890. get: function () {
  41891. return this._highlightsDensity;
  41892. },
  41893. /**
  41894. * Sets the highlights Density value.
  41895. * 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.
  41896. * Values less than zero provide a filter of opposite hue.
  41897. */
  41898. set: function (value) {
  41899. this._highlightsDensity = value;
  41900. this._dirty = true;
  41901. },
  41902. enumerable: true,
  41903. configurable: true
  41904. });
  41905. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41906. /**
  41907. * Gets the highlights Saturation value.
  41908. * 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.
  41909. */
  41910. get: function () {
  41911. return this._highlightsSaturation;
  41912. },
  41913. /**
  41914. * Sets the highlights Saturation value.
  41915. * 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.
  41916. */
  41917. set: function (value) {
  41918. this._highlightsSaturation = value;
  41919. this._dirty = true;
  41920. },
  41921. enumerable: true,
  41922. configurable: true
  41923. });
  41924. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41925. /**
  41926. * Gets the highlights Exposure value.
  41927. * 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.
  41928. */
  41929. get: function () {
  41930. return this._highlightsExposure;
  41931. },
  41932. /**
  41933. * Sets the highlights Exposure value.
  41934. * 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.
  41935. */
  41936. set: function (value) {
  41937. this._highlightsExposure = value;
  41938. this._dirty = true;
  41939. },
  41940. enumerable: true,
  41941. configurable: true
  41942. });
  41943. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41944. /**
  41945. * Gets the midtones Hue value.
  41946. * 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).
  41947. */
  41948. get: function () {
  41949. return this._midtonesHue;
  41950. },
  41951. /**
  41952. * Sets the midtones Hue value.
  41953. * 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).
  41954. */
  41955. set: function (value) {
  41956. this._midtonesHue = value;
  41957. this._dirty = true;
  41958. },
  41959. enumerable: true,
  41960. configurable: true
  41961. });
  41962. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41963. /**
  41964. * Gets the midtones Density value.
  41965. * 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.
  41966. * Values less than zero provide a filter of opposite hue.
  41967. */
  41968. get: function () {
  41969. return this._midtonesDensity;
  41970. },
  41971. /**
  41972. * Sets the midtones Density value.
  41973. * 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.
  41974. * Values less than zero provide a filter of opposite hue.
  41975. */
  41976. set: function (value) {
  41977. this._midtonesDensity = value;
  41978. this._dirty = true;
  41979. },
  41980. enumerable: true,
  41981. configurable: true
  41982. });
  41983. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41984. /**
  41985. * Gets the midtones Saturation value.
  41986. * 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.
  41987. */
  41988. get: function () {
  41989. return this._midtonesSaturation;
  41990. },
  41991. /**
  41992. * Sets the midtones Saturation value.
  41993. * 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.
  41994. */
  41995. set: function (value) {
  41996. this._midtonesSaturation = value;
  41997. this._dirty = true;
  41998. },
  41999. enumerable: true,
  42000. configurable: true
  42001. });
  42002. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  42003. /**
  42004. * Gets the midtones Exposure value.
  42005. * 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.
  42006. */
  42007. get: function () {
  42008. return this._midtonesExposure;
  42009. },
  42010. /**
  42011. * Sets the midtones Exposure value.
  42012. * 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.
  42013. */
  42014. set: function (value) {
  42015. this._midtonesExposure = value;
  42016. this._dirty = true;
  42017. },
  42018. enumerable: true,
  42019. configurable: true
  42020. });
  42021. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42022. /**
  42023. * Gets the shadows Hue value.
  42024. * 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).
  42025. */
  42026. get: function () {
  42027. return this._shadowsHue;
  42028. },
  42029. /**
  42030. * Sets the shadows Hue value.
  42031. * 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).
  42032. */
  42033. set: function (value) {
  42034. this._shadowsHue = value;
  42035. this._dirty = true;
  42036. },
  42037. enumerable: true,
  42038. configurable: true
  42039. });
  42040. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42041. /**
  42042. * Gets the shadows Density value.
  42043. * 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.
  42044. * Values less than zero provide a filter of opposite hue.
  42045. */
  42046. get: function () {
  42047. return this._shadowsDensity;
  42048. },
  42049. /**
  42050. * Sets the shadows Density value.
  42051. * 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.
  42052. * Values less than zero provide a filter of opposite hue.
  42053. */
  42054. set: function (value) {
  42055. this._shadowsDensity = value;
  42056. this._dirty = true;
  42057. },
  42058. enumerable: true,
  42059. configurable: true
  42060. });
  42061. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42062. /**
  42063. * Gets the shadows Saturation value.
  42064. * 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.
  42065. */
  42066. get: function () {
  42067. return this._shadowsSaturation;
  42068. },
  42069. /**
  42070. * Sets the shadows Saturation value.
  42071. * 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.
  42072. */
  42073. set: function (value) {
  42074. this._shadowsSaturation = value;
  42075. this._dirty = true;
  42076. },
  42077. enumerable: true,
  42078. configurable: true
  42079. });
  42080. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42081. /**
  42082. * Gets the shadows Exposure value.
  42083. * 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.
  42084. */
  42085. get: function () {
  42086. return this._shadowsExposure;
  42087. },
  42088. /**
  42089. * Sets the shadows Exposure value.
  42090. * 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.
  42091. */
  42092. set: function (value) {
  42093. this._shadowsExposure = value;
  42094. this._dirty = true;
  42095. },
  42096. enumerable: true,
  42097. configurable: true
  42098. });
  42099. ColorCurves.prototype.getClassName = function () {
  42100. return "ColorCurves";
  42101. };
  42102. /**
  42103. * Binds the color curves to the shader.
  42104. * @param colorCurves The color curve to bind
  42105. * @param effect The effect to bind to
  42106. */
  42107. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42108. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42109. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42110. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42111. if (colorCurves._dirty) {
  42112. colorCurves._dirty = false;
  42113. // Fill in global info.
  42114. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42115. // Compute highlights info.
  42116. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42117. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42118. // Compute midtones info.
  42119. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42120. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42121. // Compute shadows info.
  42122. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42123. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42124. // Compute deltas (neutral is midtones).
  42125. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42126. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42127. }
  42128. if (effect) {
  42129. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42130. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42131. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42132. }
  42133. };
  42134. /**
  42135. * Prepare the list of uniforms associated with the ColorCurves effects.
  42136. * @param uniformsList The list of uniforms used in the effect
  42137. */
  42138. ColorCurves.PrepareUniforms = function (uniformsList) {
  42139. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42140. };
  42141. /**
  42142. * Returns color grading data based on a hue, density, saturation and exposure value.
  42143. * @param filterHue The hue of the color filter.
  42144. * @param filterDensity The density of the color filter.
  42145. * @param saturation The saturation.
  42146. * @param exposure The exposure.
  42147. * @param result The result data container.
  42148. */
  42149. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42150. if (hue == null) {
  42151. return;
  42152. }
  42153. hue = ColorCurves.clamp(hue, 0, 360);
  42154. density = ColorCurves.clamp(density, -100, 100);
  42155. saturation = ColorCurves.clamp(saturation, -100, 100);
  42156. exposure = ColorCurves.clamp(exposure, -100, 100);
  42157. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42158. // so that the maximum filter density is only 50% control. This provides fine control
  42159. // for small values and reasonable range.
  42160. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42161. density *= 0.5;
  42162. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42163. if (density < 0) {
  42164. density *= -1;
  42165. hue = (hue + 180) % 360;
  42166. }
  42167. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42168. result.scaleToRef(2, result);
  42169. result.a = 1 + 0.01 * saturation;
  42170. };
  42171. /**
  42172. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42173. * @param value The input slider value in range [-100,100].
  42174. * @returns Adjusted value.
  42175. */
  42176. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42177. value /= 100;
  42178. var x = Math.abs(value);
  42179. x = Math.pow(x, 2);
  42180. if (value < 0) {
  42181. x *= -1;
  42182. }
  42183. x *= 100;
  42184. return x;
  42185. };
  42186. /**
  42187. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42188. * @param hue The hue (H) input.
  42189. * @param saturation The saturation (S) input.
  42190. * @param brightness The brightness (B) input.
  42191. * @result An RGBA color represented as Vector4.
  42192. */
  42193. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42194. var h = ColorCurves.clamp(hue, 0, 360);
  42195. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42196. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42197. if (s === 0) {
  42198. result.r = v;
  42199. result.g = v;
  42200. result.b = v;
  42201. }
  42202. else {
  42203. // sector 0 to 5
  42204. h /= 60;
  42205. var i = Math.floor(h);
  42206. // fractional part of h
  42207. var f = h - i;
  42208. var p = v * (1 - s);
  42209. var q = v * (1 - s * f);
  42210. var t = v * (1 - s * (1 - f));
  42211. switch (i) {
  42212. case 0:
  42213. result.r = v;
  42214. result.g = t;
  42215. result.b = p;
  42216. break;
  42217. case 1:
  42218. result.r = q;
  42219. result.g = v;
  42220. result.b = p;
  42221. break;
  42222. case 2:
  42223. result.r = p;
  42224. result.g = v;
  42225. result.b = t;
  42226. break;
  42227. case 3:
  42228. result.r = p;
  42229. result.g = q;
  42230. result.b = v;
  42231. break;
  42232. case 4:
  42233. result.r = t;
  42234. result.g = p;
  42235. result.b = v;
  42236. break;
  42237. default:// case 5:
  42238. result.r = v;
  42239. result.g = p;
  42240. result.b = q;
  42241. break;
  42242. }
  42243. }
  42244. result.a = 1;
  42245. };
  42246. /**
  42247. * Returns a value clamped between min and max
  42248. * @param value The value to clamp
  42249. * @param min The minimum of value
  42250. * @param max The maximum of value
  42251. * @returns The clamped value.
  42252. */
  42253. ColorCurves.clamp = function (value, min, max) {
  42254. return Math.min(Math.max(value, min), max);
  42255. };
  42256. /**
  42257. * Clones the current color curve instance.
  42258. * @return The cloned curves
  42259. */
  42260. ColorCurves.prototype.clone = function () {
  42261. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42262. };
  42263. /**
  42264. * Serializes the current color curve instance to a json representation.
  42265. * @return a JSON representation
  42266. */
  42267. ColorCurves.prototype.serialize = function () {
  42268. return BABYLON.SerializationHelper.Serialize(this);
  42269. };
  42270. /**
  42271. * Parses the color curve from a json representation.
  42272. * @param source the JSON source to parse
  42273. * @return The parsed curves
  42274. */
  42275. ColorCurves.Parse = function (source) {
  42276. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42277. };
  42278. __decorate([
  42279. BABYLON.serialize()
  42280. ], ColorCurves.prototype, "_globalHue", void 0);
  42281. __decorate([
  42282. BABYLON.serialize()
  42283. ], ColorCurves.prototype, "_globalDensity", void 0);
  42284. __decorate([
  42285. BABYLON.serialize()
  42286. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42287. __decorate([
  42288. BABYLON.serialize()
  42289. ], ColorCurves.prototype, "_globalExposure", void 0);
  42290. __decorate([
  42291. BABYLON.serialize()
  42292. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42293. __decorate([
  42294. BABYLON.serialize()
  42295. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42296. __decorate([
  42297. BABYLON.serialize()
  42298. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42299. __decorate([
  42300. BABYLON.serialize()
  42301. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42302. __decorate([
  42303. BABYLON.serialize()
  42304. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42305. __decorate([
  42306. BABYLON.serialize()
  42307. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42308. __decorate([
  42309. BABYLON.serialize()
  42310. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42311. __decorate([
  42312. BABYLON.serialize()
  42313. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42314. return ColorCurves;
  42315. }());
  42316. BABYLON.ColorCurves = ColorCurves;
  42317. })(BABYLON || (BABYLON = {}));
  42318. //# sourceMappingURL=babylon.colorCurves.js.map
  42319. var BABYLON;
  42320. (function (BABYLON) {
  42321. var PostProcessRenderPipelineManager = (function () {
  42322. function PostProcessRenderPipelineManager() {
  42323. this._renderPipelines = {};
  42324. }
  42325. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  42326. this._renderPipelines[renderPipeline._name] = renderPipeline;
  42327. };
  42328. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  42329. var renderPipeline = this._renderPipelines[renderPipelineName];
  42330. if (!renderPipeline) {
  42331. return;
  42332. }
  42333. renderPipeline._attachCameras(cameras, unique);
  42334. };
  42335. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  42336. var renderPipeline = this._renderPipelines[renderPipelineName];
  42337. if (!renderPipeline) {
  42338. return;
  42339. }
  42340. renderPipeline._detachCameras(cameras);
  42341. };
  42342. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  42343. var renderPipeline = this._renderPipelines[renderPipelineName];
  42344. if (!renderPipeline) {
  42345. return;
  42346. }
  42347. renderPipeline._enableEffect(renderEffectName, cameras);
  42348. };
  42349. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  42350. var renderPipeline = this._renderPipelines[renderPipelineName];
  42351. if (!renderPipeline) {
  42352. return;
  42353. }
  42354. renderPipeline._disableEffect(renderEffectName, cameras);
  42355. };
  42356. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  42357. var renderPipeline = this._renderPipelines[renderPipelineName];
  42358. if (!renderPipeline) {
  42359. return;
  42360. }
  42361. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  42362. };
  42363. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  42364. var renderPipeline = this._renderPipelines[renderPipelineName];
  42365. if (!renderPipeline) {
  42366. return;
  42367. }
  42368. renderPipeline._disableDisplayOnlyPass(cameras);
  42369. };
  42370. PostProcessRenderPipelineManager.prototype.update = function () {
  42371. for (var renderPipelineName in this._renderPipelines) {
  42372. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  42373. var pipeline = this._renderPipelines[renderPipelineName];
  42374. if (!pipeline.isSupported) {
  42375. pipeline.dispose();
  42376. delete this._renderPipelines[renderPipelineName];
  42377. }
  42378. else {
  42379. pipeline._update();
  42380. }
  42381. }
  42382. }
  42383. };
  42384. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  42385. for (var renderPipelineName in this._renderPipelines) {
  42386. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  42387. var pipeline = this._renderPipelines[renderPipelineName];
  42388. pipeline._rebuild();
  42389. }
  42390. }
  42391. };
  42392. PostProcessRenderPipelineManager.prototype.dispose = function () {
  42393. for (var renderPipelineName in this._renderPipelines) {
  42394. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  42395. var pipeline = this._renderPipelines[renderPipelineName];
  42396. pipeline.dispose();
  42397. }
  42398. }
  42399. };
  42400. return PostProcessRenderPipelineManager;
  42401. }());
  42402. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  42403. })(BABYLON || (BABYLON = {}));
  42404. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  42405. var BABYLON;
  42406. (function (BABYLON) {
  42407. var PostProcessRenderPass = (function () {
  42408. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  42409. this._enabled = true;
  42410. this._refCount = 0;
  42411. this._name = name;
  42412. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  42413. this.setRenderList(renderList);
  42414. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  42415. this._renderTexture.onAfterRenderObservable.add(afterRender);
  42416. this._scene = scene;
  42417. this._renderList = renderList;
  42418. }
  42419. // private
  42420. PostProcessRenderPass.prototype._incRefCount = function () {
  42421. if (this._refCount === 0) {
  42422. this._scene.customRenderTargets.push(this._renderTexture);
  42423. }
  42424. return ++this._refCount;
  42425. };
  42426. PostProcessRenderPass.prototype._decRefCount = function () {
  42427. this._refCount--;
  42428. if (this._refCount <= 0) {
  42429. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  42430. }
  42431. return this._refCount;
  42432. };
  42433. PostProcessRenderPass.prototype._update = function () {
  42434. this.setRenderList(this._renderList);
  42435. };
  42436. // public
  42437. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  42438. this._renderTexture.renderList = renderList;
  42439. };
  42440. PostProcessRenderPass.prototype.getRenderTexture = function () {
  42441. return this._renderTexture;
  42442. };
  42443. return PostProcessRenderPass;
  42444. }());
  42445. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  42446. })(BABYLON || (BABYLON = {}));
  42447. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  42448. var BABYLON;
  42449. (function (BABYLON) {
  42450. var PostProcessRenderEffect = (function () {
  42451. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  42452. this._engine = engine;
  42453. this._name = name;
  42454. this._singleInstance = singleInstance || true;
  42455. this._getPostProcess = getPostProcess;
  42456. this._cameras = [];
  42457. this._indicesForCamera = [];
  42458. this._postProcesses = {};
  42459. this._renderPasses = {};
  42460. this._renderEffectAsPasses = {};
  42461. }
  42462. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  42463. get: function () {
  42464. for (var index in this._postProcesses) {
  42465. if (!this._postProcesses[index].isSupported) {
  42466. return false;
  42467. }
  42468. }
  42469. return true;
  42470. },
  42471. enumerable: true,
  42472. configurable: true
  42473. });
  42474. PostProcessRenderEffect.prototype._update = function () {
  42475. for (var renderPassName in this._renderPasses) {
  42476. this._renderPasses[renderPassName]._update();
  42477. }
  42478. };
  42479. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  42480. this._renderPasses[renderPass._name] = renderPass;
  42481. this._linkParameters();
  42482. };
  42483. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  42484. delete this._renderPasses[renderPass._name];
  42485. this._linkParameters();
  42486. };
  42487. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  42488. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  42489. this._linkParameters();
  42490. };
  42491. PostProcessRenderEffect.prototype.getPass = function (passName) {
  42492. for (var renderPassName in this._renderPasses) {
  42493. if (renderPassName === passName) {
  42494. return this._renderPasses[passName];
  42495. }
  42496. }
  42497. };
  42498. PostProcessRenderEffect.prototype.emptyPasses = function () {
  42499. this._renderPasses = {};
  42500. this._linkParameters();
  42501. };
  42502. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  42503. var cameraKey;
  42504. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42505. for (var i = 0; i < _cam.length; i++) {
  42506. var camera = _cam[i];
  42507. var cameraName = camera.name;
  42508. if (this._singleInstance) {
  42509. cameraKey = 0;
  42510. }
  42511. else {
  42512. cameraKey = cameraName;
  42513. }
  42514. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  42515. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  42516. if (!this._indicesForCamera[cameraName]) {
  42517. this._indicesForCamera[cameraName] = [];
  42518. }
  42519. this._indicesForCamera[cameraName].push(index);
  42520. if (this._cameras.indexOf(camera) === -1) {
  42521. this._cameras[cameraName] = camera;
  42522. }
  42523. for (var passName in this._renderPasses) {
  42524. this._renderPasses[passName]._incRefCount();
  42525. }
  42526. }
  42527. this._linkParameters();
  42528. };
  42529. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  42530. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42531. for (var i = 0; i < _cam.length; i++) {
  42532. var camera = _cam[i];
  42533. var cameraName = camera.name;
  42534. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42535. var index = this._cameras.indexOf(cameraName);
  42536. this._indicesForCamera.splice(index, 1);
  42537. this._cameras.splice(index, 1);
  42538. for (var passName in this._renderPasses) {
  42539. this._renderPasses[passName]._decRefCount();
  42540. }
  42541. }
  42542. };
  42543. PostProcessRenderEffect.prototype._enable = function (cameras) {
  42544. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42545. for (var i = 0; i < _cam.length; i++) {
  42546. var camera = _cam[i];
  42547. var cameraName = camera.name;
  42548. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  42549. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  42550. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  42551. }
  42552. }
  42553. for (var passName in this._renderPasses) {
  42554. this._renderPasses[passName]._incRefCount();
  42555. }
  42556. }
  42557. };
  42558. PostProcessRenderEffect.prototype._disable = function (cameras) {
  42559. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42560. for (var i = 0; i < _cam.length; i++) {
  42561. var camera = _cam[i];
  42562. var cameraName = camera.Name;
  42563. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42564. for (var passName in this._renderPasses) {
  42565. this._renderPasses[passName]._decRefCount();
  42566. }
  42567. }
  42568. };
  42569. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  42570. if (this._singleInstance) {
  42571. return this._postProcesses[0];
  42572. }
  42573. else {
  42574. return this._postProcesses[camera.name];
  42575. }
  42576. };
  42577. PostProcessRenderEffect.prototype._linkParameters = function () {
  42578. var _this = this;
  42579. for (var index in this._postProcesses) {
  42580. if (this.applyParameters) {
  42581. this.applyParameters(this._postProcesses[index]);
  42582. }
  42583. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  42584. _this._linkTextures(effect);
  42585. });
  42586. }
  42587. };
  42588. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  42589. for (var renderPassName in this._renderPasses) {
  42590. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  42591. }
  42592. for (var renderEffectName in this._renderEffectAsPasses) {
  42593. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  42594. }
  42595. };
  42596. return PostProcessRenderEffect;
  42597. }());
  42598. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  42599. })(BABYLON || (BABYLON = {}));
  42600. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  42601. var BABYLON;
  42602. (function (BABYLON) {
  42603. var PostProcessRenderPipeline = (function () {
  42604. function PostProcessRenderPipeline(engine, name) {
  42605. this._engine = engine;
  42606. this._name = name;
  42607. this._renderEffects = new Array();
  42608. this._renderEffectsForIsolatedPass = new Array();
  42609. this._cameras = [];
  42610. }
  42611. PostProcessRenderPipeline.prototype.getClassName = function () {
  42612. return "PostProcessRenderPipeline";
  42613. };
  42614. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  42615. get: function () {
  42616. for (var renderEffectName in this._renderEffects) {
  42617. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42618. if (!this._renderEffects[renderEffectName].isSupported) {
  42619. return false;
  42620. }
  42621. }
  42622. }
  42623. return true;
  42624. },
  42625. enumerable: true,
  42626. configurable: true
  42627. });
  42628. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  42629. this._renderEffects[renderEffect._name] = renderEffect;
  42630. };
  42631. // private
  42632. PostProcessRenderPipeline.prototype._rebuild = function () {
  42633. };
  42634. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  42635. var renderEffects = this._renderEffects[renderEffectName];
  42636. if (!renderEffects) {
  42637. return;
  42638. }
  42639. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42640. };
  42641. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  42642. var renderEffects = this._renderEffects[renderEffectName];
  42643. if (!renderEffects) {
  42644. return;
  42645. }
  42646. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42647. };
  42648. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  42649. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42650. var indicesToDelete = [];
  42651. var i;
  42652. for (i = 0; i < _cam.length; i++) {
  42653. var camera = _cam[i];
  42654. var cameraName = camera.name;
  42655. if (this._cameras.indexOf(camera) === -1) {
  42656. this._cameras[cameraName] = camera;
  42657. }
  42658. else if (unique) {
  42659. indicesToDelete.push(i);
  42660. }
  42661. }
  42662. for (i = 0; i < indicesToDelete.length; i++) {
  42663. cameras.splice(indicesToDelete[i], 1);
  42664. }
  42665. for (var renderEffectName in this._renderEffects) {
  42666. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42667. this._renderEffects[renderEffectName]._attachCameras(_cam);
  42668. }
  42669. }
  42670. };
  42671. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  42672. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42673. for (var renderEffectName in this._renderEffects) {
  42674. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42675. this._renderEffects[renderEffectName]._detachCameras(_cam);
  42676. }
  42677. }
  42678. for (var i = 0; i < _cam.length; i++) {
  42679. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  42680. }
  42681. };
  42682. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  42683. var _this = this;
  42684. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42685. var pass = null;
  42686. var renderEffectName;
  42687. for (renderEffectName in this._renderEffects) {
  42688. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42689. pass = this._renderEffects[renderEffectName].getPass(passName);
  42690. if (pass != null) {
  42691. break;
  42692. }
  42693. }
  42694. }
  42695. if (pass === null) {
  42696. return;
  42697. }
  42698. for (renderEffectName in this._renderEffects) {
  42699. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42700. this._renderEffects[renderEffectName]._disable(_cam);
  42701. }
  42702. }
  42703. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  42704. for (var i = 0; i < _cam.length; i++) {
  42705. var camera = _cam[i];
  42706. var cameraName = camera.name;
  42707. 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); });
  42708. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  42709. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  42710. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  42711. }
  42712. };
  42713. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  42714. var _this = this;
  42715. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42716. for (var i = 0; i < _cam.length; i++) {
  42717. var camera = _cam[i];
  42718. var cameraName = camera.name;
  42719. 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); });
  42720. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  42721. }
  42722. for (var renderEffectName in this._renderEffects) {
  42723. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42724. this._renderEffects[renderEffectName]._enable(_cam);
  42725. }
  42726. }
  42727. };
  42728. PostProcessRenderPipeline.prototype._update = function () {
  42729. for (var renderEffectName in this._renderEffects) {
  42730. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42731. this._renderEffects[renderEffectName]._update();
  42732. }
  42733. }
  42734. for (var i = 0; i < this._cameras.length; i++) {
  42735. var cameraName = this._cameras[i].name;
  42736. if (this._renderEffectsForIsolatedPass[cameraName]) {
  42737. this._renderEffectsForIsolatedPass[cameraName]._update();
  42738. }
  42739. }
  42740. };
  42741. PostProcessRenderPipeline.prototype._reset = function () {
  42742. this._renderEffects = new Array();
  42743. this._renderEffectsForIsolatedPass = new Array();
  42744. };
  42745. PostProcessRenderPipeline.prototype.dispose = function () {
  42746. // Must be implemented by children
  42747. };
  42748. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  42749. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  42750. __decorate([
  42751. BABYLON.serialize()
  42752. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  42753. return PostProcessRenderPipeline;
  42754. }());
  42755. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  42756. })(BABYLON || (BABYLON = {}));
  42757. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  42758. var BABYLON;
  42759. (function (BABYLON) {
  42760. var DefaultRenderingPipeline = (function (_super) {
  42761. __extends(DefaultRenderingPipeline, _super);
  42762. /**
  42763. * @constructor
  42764. * @param {string} name - The rendering pipeline name
  42765. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  42766. * @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)
  42767. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  42768. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  42769. */
  42770. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  42771. if (automaticBuild === void 0) { automaticBuild = true; }
  42772. var _this = _super.call(this, scene.getEngine(), name) || this;
  42773. _this.PassPostProcessId = "PassPostProcessEffect";
  42774. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  42775. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  42776. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  42777. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  42778. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  42779. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  42780. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  42781. // IAnimatable
  42782. _this.animations = [];
  42783. // Values
  42784. _this._bloomEnabled = false;
  42785. _this._fxaaEnabled = false;
  42786. _this._imageProcessingEnabled = true;
  42787. _this._bloomScale = 0.6;
  42788. _this._buildAllowed = true;
  42789. /**
  42790. * Specifies the size of the bloom blur kernel, relative to the final output size
  42791. */
  42792. _this.bloomKernel = 64;
  42793. /**
  42794. * Specifies the weight of the bloom in the final rendering
  42795. */
  42796. _this._bloomWeight = 0.15;
  42797. _this._cameras = cameras || [];
  42798. _this._buildAllowed = automaticBuild;
  42799. // Initialize
  42800. _this._scene = scene;
  42801. var caps = _this._scene.getEngine().getCaps();
  42802. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  42803. // Misc
  42804. if (_this._hdr) {
  42805. if (caps.textureHalfFloatRender) {
  42806. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  42807. }
  42808. else if (caps.textureFloatRender) {
  42809. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42810. }
  42811. }
  42812. else {
  42813. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42814. }
  42815. // Attach
  42816. scene.postProcessRenderPipelineManager.addPipeline(_this);
  42817. _this._buildPipeline();
  42818. return _this;
  42819. }
  42820. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  42821. get: function () {
  42822. return this._bloomWeight;
  42823. },
  42824. set: function (value) {
  42825. if (this._bloomWeight === value) {
  42826. return;
  42827. }
  42828. this._bloomWeight = value;
  42829. if (this._hdr && this.copyBack) {
  42830. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  42831. }
  42832. },
  42833. enumerable: true,
  42834. configurable: true
  42835. });
  42836. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  42837. get: function () {
  42838. return this._bloomScale;
  42839. },
  42840. set: function (value) {
  42841. if (this._bloomScale === value) {
  42842. return;
  42843. }
  42844. this._bloomScale = value;
  42845. this._buildPipeline();
  42846. },
  42847. enumerable: true,
  42848. configurable: true
  42849. });
  42850. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  42851. get: function () {
  42852. return this._bloomEnabled;
  42853. },
  42854. set: function (enabled) {
  42855. if (this._bloomEnabled === enabled) {
  42856. return;
  42857. }
  42858. this._bloomEnabled = enabled;
  42859. this._buildPipeline();
  42860. },
  42861. enumerable: true,
  42862. configurable: true
  42863. });
  42864. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  42865. get: function () {
  42866. return this._fxaaEnabled;
  42867. },
  42868. set: function (enabled) {
  42869. if (this._fxaaEnabled === enabled) {
  42870. return;
  42871. }
  42872. this._fxaaEnabled = enabled;
  42873. this._buildPipeline();
  42874. },
  42875. enumerable: true,
  42876. configurable: true
  42877. });
  42878. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  42879. get: function () {
  42880. return this._imageProcessingEnabled;
  42881. },
  42882. set: function (enabled) {
  42883. if (this._imageProcessingEnabled === enabled) {
  42884. return;
  42885. }
  42886. this._imageProcessingEnabled = enabled;
  42887. this._buildPipeline();
  42888. },
  42889. enumerable: true,
  42890. configurable: true
  42891. });
  42892. /**
  42893. * Force the compilation of the entire pipeline.
  42894. */
  42895. DefaultRenderingPipeline.prototype.prepare = function () {
  42896. var previousState = this._buildAllowed;
  42897. this._buildAllowed = true;
  42898. this._buildPipeline();
  42899. this._buildAllowed = previousState;
  42900. };
  42901. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  42902. var _this = this;
  42903. if (!this._buildAllowed) {
  42904. return;
  42905. }
  42906. var engine = this._scene.getEngine();
  42907. this._disposePostProcesses();
  42908. this._reset();
  42909. if (this.bloomEnabled) {
  42910. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42911. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  42912. if (!this._hdr) {
  42913. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42914. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  42915. this.highlights.autoClear = false;
  42916. this.highlights.alwaysForcePOT = true;
  42917. }
  42918. 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);
  42919. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  42920. this.blurX.alwaysForcePOT = true;
  42921. this.blurX.autoClear = false;
  42922. this.blurX.onActivateObservable.add(function () {
  42923. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  42924. _this.blurX.kernel = _this.bloomKernel * dw;
  42925. });
  42926. 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);
  42927. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  42928. this.blurY.alwaysForcePOT = true;
  42929. this.blurY.autoClear = false;
  42930. this.blurY.onActivateObservable.add(function () {
  42931. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  42932. _this.blurY.kernel = _this.bloomKernel * dh;
  42933. });
  42934. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42935. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  42936. this.copyBack.alwaysForcePOT = true;
  42937. if (this._hdr) {
  42938. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  42939. var w = this.bloomWeight;
  42940. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  42941. }
  42942. else {
  42943. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  42944. }
  42945. this.copyBack.autoClear = false;
  42946. }
  42947. if (this._imageProcessingEnabled) {
  42948. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42949. if (this._hdr) {
  42950. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  42951. }
  42952. }
  42953. if (this.fxaaEnabled) {
  42954. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42955. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  42956. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  42957. }
  42958. else {
  42959. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42960. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  42961. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  42962. }
  42963. if (this.bloomEnabled) {
  42964. if (this._hdr) {
  42965. this.copyBack.shareOutputWith(this.blurX);
  42966. if (this.imageProcessing) {
  42967. this.imageProcessing.shareOutputWith(this.pass);
  42968. this.imageProcessing.autoClear = false;
  42969. }
  42970. else if (this.fxaa) {
  42971. this.fxaa.shareOutputWith(this.pass);
  42972. }
  42973. else {
  42974. this.finalMerge.shareOutputWith(this.pass);
  42975. }
  42976. }
  42977. else {
  42978. if (this.fxaa) {
  42979. this.fxaa.shareOutputWith(this.pass);
  42980. }
  42981. else {
  42982. this.finalMerge.shareOutputWith(this.pass);
  42983. }
  42984. }
  42985. }
  42986. if (this._cameras !== null) {
  42987. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  42988. }
  42989. };
  42990. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  42991. for (var i = 0; i < this._cameras.length; i++) {
  42992. var camera = this._cameras[i];
  42993. if (this.pass) {
  42994. this.pass.dispose(camera);
  42995. }
  42996. if (this.highlights) {
  42997. this.highlights.dispose(camera);
  42998. }
  42999. if (this.blurX) {
  43000. this.blurX.dispose(camera);
  43001. }
  43002. if (this.blurY) {
  43003. this.blurY.dispose(camera);
  43004. }
  43005. if (this.copyBack) {
  43006. this.copyBack.dispose(camera);
  43007. }
  43008. if (this.imageProcessing) {
  43009. this.imageProcessing.dispose(camera);
  43010. }
  43011. if (this.fxaa) {
  43012. this.fxaa.dispose(camera);
  43013. }
  43014. if (this.finalMerge) {
  43015. this.finalMerge.dispose(camera);
  43016. }
  43017. }
  43018. this.pass = null;
  43019. this.highlights = null;
  43020. this.blurX = null;
  43021. this.blurY = null;
  43022. this.copyBack = null;
  43023. this.imageProcessing = null;
  43024. this.fxaa = null;
  43025. this.finalMerge = null;
  43026. };
  43027. // Dispose
  43028. DefaultRenderingPipeline.prototype.dispose = function () {
  43029. this._disposePostProcesses();
  43030. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  43031. _super.prototype.dispose.call(this);
  43032. };
  43033. // Serialize rendering pipeline
  43034. DefaultRenderingPipeline.prototype.serialize = function () {
  43035. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43036. serializationObject.customType = "DefaultRenderingPipeline";
  43037. return serializationObject;
  43038. };
  43039. // Parse serialized pipeline
  43040. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  43041. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  43042. };
  43043. __decorate([
  43044. BABYLON.serialize()
  43045. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  43046. __decorate([
  43047. BABYLON.serialize()
  43048. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  43049. __decorate([
  43050. BABYLON.serialize()
  43051. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  43052. __decorate([
  43053. BABYLON.serialize()
  43054. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  43055. __decorate([
  43056. BABYLON.serialize()
  43057. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  43058. __decorate([
  43059. BABYLON.serialize()
  43060. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  43061. __decorate([
  43062. BABYLON.serialize()
  43063. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  43064. __decorate([
  43065. BABYLON.serialize()
  43066. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  43067. return DefaultRenderingPipeline;
  43068. }(BABYLON.PostProcessRenderPipeline));
  43069. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  43070. })(BABYLON || (BABYLON = {}));
  43071. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  43072. var BABYLON;
  43073. (function (BABYLON) {
  43074. /**
  43075. * This groups together the common properties used for image processing either in direct forward pass
  43076. * or through post processing effect depending on the use of the image processing pipeline in your scene
  43077. * or not.
  43078. */
  43079. var ImageProcessingConfiguration = (function () {
  43080. function ImageProcessingConfiguration() {
  43081. /**
  43082. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  43083. */
  43084. this.colorCurves = new BABYLON.ColorCurves();
  43085. this._colorCurvesEnabled = false;
  43086. this._colorGradingEnabled = false;
  43087. this._colorGradingWithGreenDepth = false;
  43088. this._colorGradingBGR = false;
  43089. this._exposure = 1.0;
  43090. this._toneMappingEnabled = false;
  43091. this._contrast = 1.0;
  43092. /**
  43093. * Vignette stretch size.
  43094. */
  43095. this.vignetteStretch = 0;
  43096. /**
  43097. * Vignette centre X Offset.
  43098. */
  43099. this.vignetteCentreX = 0;
  43100. /**
  43101. * Vignette centre Y Offset.
  43102. */
  43103. this.vignetteCentreY = 0;
  43104. /**
  43105. * Vignette weight or intensity of the vignette effect.
  43106. */
  43107. this.vignetteWeight = 1.5;
  43108. /**
  43109. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  43110. * if vignetteEnabled is set to true.
  43111. */
  43112. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  43113. /**
  43114. * Camera field of view used by the Vignette effect.
  43115. */
  43116. this.vignetteCameraFov = 0.5;
  43117. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  43118. this._vignetteEnabled = false;
  43119. this._applyByPostProcess = false;
  43120. /**
  43121. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  43122. * @type {BABYLON.Observable}
  43123. */
  43124. this.onUpdateParameters = new BABYLON.Observable();
  43125. }
  43126. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  43127. /**
  43128. * Gets wether the color curves effect is enabled.
  43129. */
  43130. get: function () {
  43131. return this._colorCurvesEnabled;
  43132. },
  43133. /**
  43134. * Sets wether the color curves effect is enabled.
  43135. */
  43136. set: function (value) {
  43137. if (this._colorCurvesEnabled === value) {
  43138. return;
  43139. }
  43140. this._colorCurvesEnabled = value;
  43141. this._updateParameters();
  43142. },
  43143. enumerable: true,
  43144. configurable: true
  43145. });
  43146. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  43147. /**
  43148. * Gets wether the color grading effect is enabled.
  43149. */
  43150. get: function () {
  43151. return this._colorGradingEnabled;
  43152. },
  43153. /**
  43154. * Sets wether the color grading effect is enabled.
  43155. */
  43156. set: function (value) {
  43157. if (this._colorGradingEnabled === value) {
  43158. return;
  43159. }
  43160. this._colorGradingEnabled = value;
  43161. this._updateParameters();
  43162. },
  43163. enumerable: true,
  43164. configurable: true
  43165. });
  43166. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  43167. /**
  43168. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  43169. */
  43170. get: function () {
  43171. return this._colorGradingWithGreenDepth;
  43172. },
  43173. /**
  43174. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  43175. */
  43176. set: function (value) {
  43177. if (this._colorGradingWithGreenDepth === value) {
  43178. return;
  43179. }
  43180. this._colorGradingWithGreenDepth = value;
  43181. this._updateParameters();
  43182. },
  43183. enumerable: true,
  43184. configurable: true
  43185. });
  43186. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  43187. /**
  43188. * Gets wether the color grading texture contains BGR values.
  43189. */
  43190. get: function () {
  43191. return this._colorGradingBGR;
  43192. },
  43193. /**
  43194. * Sets wether the color grading texture contains BGR values.
  43195. */
  43196. set: function (value) {
  43197. if (this._colorGradingBGR === value) {
  43198. return;
  43199. }
  43200. this._colorGradingBGR = value;
  43201. this._updateParameters();
  43202. },
  43203. enumerable: true,
  43204. configurable: true
  43205. });
  43206. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  43207. /**
  43208. * Gets the Exposure used in the effect.
  43209. */
  43210. get: function () {
  43211. return this._exposure;
  43212. },
  43213. /**
  43214. * Sets the Exposure used in the effect.
  43215. */
  43216. set: function (value) {
  43217. if (this._exposure === value) {
  43218. return;
  43219. }
  43220. this._exposure = value;
  43221. this._updateParameters();
  43222. },
  43223. enumerable: true,
  43224. configurable: true
  43225. });
  43226. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  43227. /**
  43228. * Gets wether the tone mapping effect is enabled.
  43229. */
  43230. get: function () {
  43231. return this._toneMappingEnabled;
  43232. },
  43233. /**
  43234. * Sets wether the tone mapping effect is enabled.
  43235. */
  43236. set: function (value) {
  43237. if (this._toneMappingEnabled === value) {
  43238. return;
  43239. }
  43240. this._toneMappingEnabled = value;
  43241. this._updateParameters();
  43242. },
  43243. enumerable: true,
  43244. configurable: true
  43245. });
  43246. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  43247. /**
  43248. * Gets the contrast used in the effect.
  43249. */
  43250. get: function () {
  43251. return this._contrast;
  43252. },
  43253. /**
  43254. * Sets the contrast used in the effect.
  43255. */
  43256. set: function (value) {
  43257. if (this._contrast === value) {
  43258. return;
  43259. }
  43260. this._contrast = value;
  43261. this._updateParameters();
  43262. },
  43263. enumerable: true,
  43264. configurable: true
  43265. });
  43266. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  43267. /**
  43268. * Gets the vignette blend mode allowing different kind of effect.
  43269. */
  43270. get: function () {
  43271. return this._vignetteBlendMode;
  43272. },
  43273. /**
  43274. * Sets the vignette blend mode allowing different kind of effect.
  43275. */
  43276. set: function (value) {
  43277. if (this._vignetteBlendMode === value) {
  43278. return;
  43279. }
  43280. this._vignetteBlendMode = value;
  43281. this._updateParameters();
  43282. },
  43283. enumerable: true,
  43284. configurable: true
  43285. });
  43286. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  43287. /**
  43288. * Gets wether the vignette effect is enabled.
  43289. */
  43290. get: function () {
  43291. return this._vignetteEnabled;
  43292. },
  43293. /**
  43294. * Sets wether the vignette effect is enabled.
  43295. */
  43296. set: function (value) {
  43297. if (this._vignetteEnabled === value) {
  43298. return;
  43299. }
  43300. this._vignetteEnabled = value;
  43301. this._updateParameters();
  43302. },
  43303. enumerable: true,
  43304. configurable: true
  43305. });
  43306. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  43307. /**
  43308. * Gets wether the image processing is applied through a post process or not.
  43309. */
  43310. get: function () {
  43311. return this._applyByPostProcess;
  43312. },
  43313. /**
  43314. * Sets wether the image processing is applied through a post process or not.
  43315. */
  43316. set: function (value) {
  43317. if (this._applyByPostProcess === value) {
  43318. return;
  43319. }
  43320. this._applyByPostProcess = value;
  43321. this._updateParameters();
  43322. },
  43323. enumerable: true,
  43324. configurable: true
  43325. });
  43326. /**
  43327. * Method called each time the image processing information changes requires to recompile the effect.
  43328. */
  43329. ImageProcessingConfiguration.prototype._updateParameters = function () {
  43330. this.onUpdateParameters.notifyObservers(this);
  43331. };
  43332. ImageProcessingConfiguration.prototype.getClassName = function () {
  43333. return "ImageProcessingConfiguration";
  43334. };
  43335. /**
  43336. * Prepare the list of uniforms associated with the Image Processing effects.
  43337. * @param uniformsList The list of uniforms used in the effect
  43338. * @param defines the list of defines currently in use
  43339. */
  43340. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  43341. if (defines.EXPOSURE) {
  43342. uniforms.push("exposureLinear");
  43343. }
  43344. if (defines.CONTRAST) {
  43345. uniforms.push("contrast");
  43346. }
  43347. if (defines.COLORGRADING) {
  43348. uniforms.push("colorTransformSettings");
  43349. }
  43350. if (defines.VIGNETTE) {
  43351. uniforms.push("vInverseScreenSize");
  43352. uniforms.push("vignetteSettings1");
  43353. uniforms.push("vignetteSettings2");
  43354. }
  43355. if (defines.COLORCURVES) {
  43356. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  43357. }
  43358. };
  43359. /**
  43360. * Prepare the list of samplers associated with the Image Processing effects.
  43361. * @param uniformsList The list of uniforms used in the effect
  43362. * @param defines the list of defines currently in use
  43363. */
  43364. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  43365. if (defines.COLORGRADING) {
  43366. samplersList.push("txColorTransform");
  43367. }
  43368. };
  43369. /**
  43370. * Prepare the list of defines associated to the shader.
  43371. * @param defines the list of defines to complete
  43372. */
  43373. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  43374. defines.VIGNETTE = this.vignetteEnabled;
  43375. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  43376. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  43377. defines.TONEMAPPING = this.toneMappingEnabled;
  43378. defines.CONTRAST = (this.contrast !== 1.0);
  43379. defines.EXPOSURE = (this.exposure !== 1.0);
  43380. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  43381. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  43382. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  43383. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  43384. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  43385. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  43386. };
  43387. /**
  43388. * Returns true if all the image processing information are ready.
  43389. */
  43390. ImageProcessingConfiguration.prototype.isReady = function () {
  43391. // Color Grading texure can not be none blocking.
  43392. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  43393. };
  43394. /**
  43395. * Binds the image processing to the shader.
  43396. * @param effect The effect to bind to
  43397. */
  43398. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  43399. if (aspectRatio === void 0) { aspectRatio = 1; }
  43400. // Color Curves
  43401. if (this._colorCurvesEnabled) {
  43402. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  43403. }
  43404. // Vignette
  43405. if (this._vignetteEnabled) {
  43406. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  43407. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  43408. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  43409. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  43410. var vignetteScaleX = vignetteScaleY * aspectRatio;
  43411. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  43412. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  43413. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  43414. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  43415. var vignettePower = -2.0 * this.vignetteWeight;
  43416. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  43417. }
  43418. // Exposure
  43419. effect.setFloat("exposureLinear", this.exposure);
  43420. // Contrast
  43421. effect.setFloat("contrast", this.contrast);
  43422. // Color transform settings
  43423. if (this.colorGradingTexture) {
  43424. effect.setTexture("txColorTransform", this.colorGradingTexture);
  43425. var textureSize = this.colorGradingTexture.getSize().height;
  43426. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  43427. 0.5 / textureSize, // textureOffset
  43428. textureSize, // textureSize
  43429. this.colorGradingTexture.level // weight
  43430. );
  43431. }
  43432. };
  43433. /**
  43434. * Clones the current image processing instance.
  43435. * @return The cloned image processing
  43436. */
  43437. ImageProcessingConfiguration.prototype.clone = function () {
  43438. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  43439. };
  43440. /**
  43441. * Serializes the current image processing instance to a json representation.
  43442. * @return a JSON representation
  43443. */
  43444. ImageProcessingConfiguration.prototype.serialize = function () {
  43445. return BABYLON.SerializationHelper.Serialize(this);
  43446. };
  43447. /**
  43448. * Parses the image processing from a json representation.
  43449. * @param source the JSON source to parse
  43450. * @return The parsed image processing
  43451. */
  43452. ImageProcessingConfiguration.Parse = function (source) {
  43453. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  43454. };
  43455. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  43456. /**
  43457. * Used to apply the vignette as a mix with the pixel color.
  43458. */
  43459. get: function () {
  43460. return this._VIGNETTEMODE_MULTIPLY;
  43461. },
  43462. enumerable: true,
  43463. configurable: true
  43464. });
  43465. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  43466. /**
  43467. * Used to apply the vignette as a replacement of the pixel color.
  43468. */
  43469. get: function () {
  43470. return this._VIGNETTEMODE_OPAQUE;
  43471. },
  43472. enumerable: true,
  43473. configurable: true
  43474. });
  43475. // Static constants associated to the image processing.
  43476. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  43477. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  43478. __decorate([
  43479. BABYLON.serializeAsColorCurves()
  43480. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  43481. __decorate([
  43482. BABYLON.serialize()
  43483. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  43484. __decorate([
  43485. BABYLON.serializeAsTexture()
  43486. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  43487. __decorate([
  43488. BABYLON.serialize()
  43489. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  43490. __decorate([
  43491. BABYLON.serialize()
  43492. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  43493. __decorate([
  43494. BABYLON.serialize()
  43495. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  43496. __decorate([
  43497. BABYLON.serialize()
  43498. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  43499. __decorate([
  43500. BABYLON.serialize()
  43501. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  43502. __decorate([
  43503. BABYLON.serialize()
  43504. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  43505. __decorate([
  43506. BABYLON.serialize()
  43507. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  43508. __decorate([
  43509. BABYLON.serialize()
  43510. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  43511. __decorate([
  43512. BABYLON.serialize()
  43513. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  43514. __decorate([
  43515. BABYLON.serialize()
  43516. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  43517. __decorate([
  43518. BABYLON.serializeAsColor4()
  43519. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  43520. __decorate([
  43521. BABYLON.serialize()
  43522. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  43523. __decorate([
  43524. BABYLON.serialize()
  43525. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  43526. __decorate([
  43527. BABYLON.serialize()
  43528. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  43529. __decorate([
  43530. BABYLON.serialize()
  43531. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  43532. return ImageProcessingConfiguration;
  43533. }());
  43534. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  43535. })(BABYLON || (BABYLON = {}));
  43536. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  43537. /// <reference path="babylon.mesh.ts" />
  43538. var BABYLON;
  43539. (function (BABYLON) {
  43540. var GroundMesh = (function (_super) {
  43541. __extends(GroundMesh, _super);
  43542. function GroundMesh(name, scene) {
  43543. var _this = _super.call(this, name, scene) || this;
  43544. _this.generateOctree = false;
  43545. _this._worldInverse = new BABYLON.Matrix();
  43546. return _this;
  43547. }
  43548. GroundMesh.prototype.getClassName = function () {
  43549. return "GroundMesh";
  43550. };
  43551. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  43552. get: function () {
  43553. return Math.min(this._subdivisionsX, this._subdivisionsY);
  43554. },
  43555. enumerable: true,
  43556. configurable: true
  43557. });
  43558. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  43559. get: function () {
  43560. return this._subdivisionsX;
  43561. },
  43562. enumerable: true,
  43563. configurable: true
  43564. });
  43565. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  43566. get: function () {
  43567. return this._subdivisionsY;
  43568. },
  43569. enumerable: true,
  43570. configurable: true
  43571. });
  43572. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  43573. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  43574. this._subdivisionsX = chunksCount;
  43575. this._subdivisionsY = chunksCount;
  43576. this.subdivide(chunksCount);
  43577. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  43578. };
  43579. /**
  43580. * Returns a height (y) value in the Worl system :
  43581. * the ground altitude at the coordinates (x, z) expressed in the World system.
  43582. * Returns the ground y position if (x, z) are outside the ground surface.
  43583. */
  43584. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  43585. var world = this.getWorldMatrix();
  43586. var invMat = BABYLON.Tmp.Matrix[5];
  43587. world.invertToRef(invMat);
  43588. var tmpVect = BABYLON.Tmp.Vector3[8];
  43589. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  43590. x = tmpVect.x;
  43591. z = tmpVect.z;
  43592. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43593. return this.position.y;
  43594. }
  43595. if (!this._heightQuads || this._heightQuads.length == 0) {
  43596. this._initHeightQuads();
  43597. this._computeHeightQuads();
  43598. }
  43599. var facet = this._getFacetAt(x, z);
  43600. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  43601. // return y in the World system
  43602. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  43603. return tmpVect.y;
  43604. };
  43605. /**
  43606. * Returns a normalized vector (Vector3) orthogonal to the ground
  43607. * at the ground coordinates (x, z) expressed in the World system.
  43608. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  43609. */
  43610. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  43611. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  43612. this.getNormalAtCoordinatesToRef(x, z, normal);
  43613. return normal;
  43614. };
  43615. /**
  43616. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  43617. * at the ground coordinates (x, z) expressed in the World system.
  43618. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  43619. * Returns the GroundMesh.
  43620. */
  43621. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  43622. var world = this.getWorldMatrix();
  43623. var tmpMat = BABYLON.Tmp.Matrix[5];
  43624. world.invertToRef(tmpMat);
  43625. var tmpVect = BABYLON.Tmp.Vector3[8];
  43626. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  43627. x = tmpVect.x;
  43628. z = tmpVect.z;
  43629. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43630. return this;
  43631. }
  43632. if (!this._heightQuads || this._heightQuads.length == 0) {
  43633. this._initHeightQuads();
  43634. this._computeHeightQuads();
  43635. }
  43636. var facet = this._getFacetAt(x, z);
  43637. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  43638. return this;
  43639. };
  43640. /**
  43641. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  43642. * if the ground has been updated.
  43643. * This can be used in the render loop.
  43644. * Returns the GroundMesh.
  43645. */
  43646. GroundMesh.prototype.updateCoordinateHeights = function () {
  43647. if (!this._heightQuads || this._heightQuads.length == 0) {
  43648. this._initHeightQuads();
  43649. }
  43650. this._computeHeightQuads();
  43651. return this;
  43652. };
  43653. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  43654. GroundMesh.prototype._getFacetAt = function (x, z) {
  43655. // retrieve col and row from x, z coordinates in the ground local system
  43656. var subdivisionsX = this._subdivisionsX;
  43657. var subdivisionsY = this._subdivisionsY;
  43658. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  43659. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  43660. var quad = this._heightQuads[row * this._subdivisionsX + col];
  43661. var facet;
  43662. if (z < quad.slope.x * x + quad.slope.y) {
  43663. facet = quad.facet1;
  43664. }
  43665. else {
  43666. facet = quad.facet2;
  43667. }
  43668. return facet;
  43669. };
  43670. // Creates and populates the heightMap array with "facet" elements :
  43671. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  43672. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43673. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43674. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43675. // Returns the GroundMesh.
  43676. GroundMesh.prototype._initHeightQuads = function () {
  43677. var subdivisionsX = this._subdivisionsX;
  43678. var subdivisionsY = this._subdivisionsY;
  43679. this._heightQuads = new Array();
  43680. for (var row = 0; row < subdivisionsY; row++) {
  43681. for (var col = 0; col < subdivisionsX; col++) {
  43682. 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) };
  43683. this._heightQuads[row * subdivisionsX + col] = quad;
  43684. }
  43685. }
  43686. return this;
  43687. };
  43688. // Compute each quad element values and update the the heightMap array :
  43689. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43690. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43691. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43692. // Returns the GroundMesh.
  43693. GroundMesh.prototype._computeHeightQuads = function () {
  43694. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43695. var v1 = BABYLON.Tmp.Vector3[3];
  43696. var v2 = BABYLON.Tmp.Vector3[2];
  43697. var v3 = BABYLON.Tmp.Vector3[1];
  43698. var v4 = BABYLON.Tmp.Vector3[0];
  43699. var v1v2 = BABYLON.Tmp.Vector3[4];
  43700. var v1v3 = BABYLON.Tmp.Vector3[5];
  43701. var v1v4 = BABYLON.Tmp.Vector3[6];
  43702. var norm1 = BABYLON.Tmp.Vector3[7];
  43703. var norm2 = BABYLON.Tmp.Vector3[8];
  43704. var i = 0;
  43705. var j = 0;
  43706. var k = 0;
  43707. var cd = 0; // 2D slope coefficient : z = cd * x + h
  43708. var h = 0;
  43709. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  43710. var d2 = 0;
  43711. var subdivisionsX = this._subdivisionsX;
  43712. var subdivisionsY = this._subdivisionsY;
  43713. for (var row = 0; row < subdivisionsY; row++) {
  43714. for (var col = 0; col < subdivisionsX; col++) {
  43715. i = col * 3;
  43716. j = row * (subdivisionsX + 1) * 3;
  43717. k = (row + 1) * (subdivisionsX + 1) * 3;
  43718. v1.x = positions[j + i];
  43719. v1.y = positions[j + i + 1];
  43720. v1.z = positions[j + i + 2];
  43721. v2.x = positions[j + i + 3];
  43722. v2.y = positions[j + i + 4];
  43723. v2.z = positions[j + i + 5];
  43724. v3.x = positions[k + i];
  43725. v3.y = positions[k + i + 1];
  43726. v3.z = positions[k + i + 2];
  43727. v4.x = positions[k + i + 3];
  43728. v4.y = positions[k + i + 4];
  43729. v4.z = positions[k + i + 5];
  43730. // 2D slope V1V4
  43731. cd = (v4.z - v1.z) / (v4.x - v1.x);
  43732. h = v1.z - cd * v1.x; // v1 belongs to the slope
  43733. // facet equations :
  43734. // we compute each facet normal vector
  43735. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  43736. // we compute the value d by applying the equation to v1 which belongs to the plane
  43737. // then we store the facet equation in a Vector4
  43738. v2.subtractToRef(v1, v1v2);
  43739. v3.subtractToRef(v1, v1v3);
  43740. v4.subtractToRef(v1, v1v4);
  43741. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  43742. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  43743. norm1.normalize();
  43744. norm2.normalize();
  43745. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  43746. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  43747. var quad = this._heightQuads[row * subdivisionsX + col];
  43748. quad.slope.copyFromFloats(cd, h);
  43749. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  43750. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  43751. }
  43752. }
  43753. return this;
  43754. };
  43755. GroundMesh.prototype.serialize = function (serializationObject) {
  43756. _super.prototype.serialize.call(this, serializationObject);
  43757. serializationObject.subdivisionsX = this._subdivisionsX;
  43758. serializationObject.subdivisionsY = this._subdivisionsY;
  43759. serializationObject.minX = this._minX;
  43760. serializationObject.maxX = this._maxX;
  43761. serializationObject.minZ = this._minZ;
  43762. serializationObject.maxZ = this._maxZ;
  43763. serializationObject.width = this._width;
  43764. serializationObject.height = this._height;
  43765. };
  43766. GroundMesh.Parse = function (parsedMesh, scene) {
  43767. var result = new GroundMesh(parsedMesh.name, scene);
  43768. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  43769. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  43770. result._minX = parsedMesh.minX;
  43771. result._maxX = parsedMesh.maxX;
  43772. result._minZ = parsedMesh.minZ;
  43773. result._maxZ = parsedMesh.maxZ;
  43774. result._width = parsedMesh.width;
  43775. result._height = parsedMesh.height;
  43776. return result;
  43777. };
  43778. return GroundMesh;
  43779. }(BABYLON.Mesh));
  43780. BABYLON.GroundMesh = GroundMesh;
  43781. })(BABYLON || (BABYLON = {}));
  43782. //# sourceMappingURL=babylon.groundMesh.js.map
  43783. var BABYLON;
  43784. (function (BABYLON) {
  43785. /**
  43786. * Creates an instance based on a source mesh.
  43787. */
  43788. var InstancedMesh = (function (_super) {
  43789. __extends(InstancedMesh, _super);
  43790. function InstancedMesh(name, source) {
  43791. var _this = _super.call(this, name, source.getScene()) || this;
  43792. source.instances.push(_this);
  43793. _this._sourceMesh = source;
  43794. _this.position.copyFrom(source.position);
  43795. _this.rotation.copyFrom(source.rotation);
  43796. _this.scaling.copyFrom(source.scaling);
  43797. if (source.rotationQuaternion) {
  43798. _this.rotationQuaternion = source.rotationQuaternion.clone();
  43799. }
  43800. _this.infiniteDistance = source.infiniteDistance;
  43801. _this.setPivotMatrix(source.getPivotMatrix());
  43802. _this.refreshBoundingInfo();
  43803. _this._syncSubMeshes();
  43804. return _this;
  43805. }
  43806. /**
  43807. * Returns the string "InstancedMesh".
  43808. */
  43809. InstancedMesh.prototype.getClassName = function () {
  43810. return "InstancedMesh";
  43811. };
  43812. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  43813. // Methods
  43814. get: function () {
  43815. return this._sourceMesh.receiveShadows;
  43816. },
  43817. enumerable: true,
  43818. configurable: true
  43819. });
  43820. Object.defineProperty(InstancedMesh.prototype, "material", {
  43821. get: function () {
  43822. return this._sourceMesh.material;
  43823. },
  43824. enumerable: true,
  43825. configurable: true
  43826. });
  43827. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  43828. get: function () {
  43829. return this._sourceMesh.visibility;
  43830. },
  43831. enumerable: true,
  43832. configurable: true
  43833. });
  43834. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  43835. get: function () {
  43836. return this._sourceMesh.skeleton;
  43837. },
  43838. enumerable: true,
  43839. configurable: true
  43840. });
  43841. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  43842. get: function () {
  43843. return this._sourceMesh.renderingGroupId;
  43844. },
  43845. enumerable: true,
  43846. configurable: true
  43847. });
  43848. /**
  43849. * Returns the total number of vertices (integer).
  43850. */
  43851. InstancedMesh.prototype.getTotalVertices = function () {
  43852. return this._sourceMesh.getTotalVertices();
  43853. };
  43854. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  43855. get: function () {
  43856. return this._sourceMesh;
  43857. },
  43858. enumerable: true,
  43859. configurable: true
  43860. });
  43861. /**
  43862. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  43863. */
  43864. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  43865. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  43866. };
  43867. /**
  43868. * Sets the vertex data of the mesh geometry for the requested `kind`.
  43869. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  43870. * The `data` are either a numeric array either a Float32Array.
  43871. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  43872. * 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).
  43873. * Note that a new underlying VertexBuffer object is created each call.
  43874. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  43875. *
  43876. * Possible `kind` values :
  43877. * - BABYLON.VertexBuffer.PositionKind
  43878. * - BABYLON.VertexBuffer.UVKind
  43879. * - BABYLON.VertexBuffer.UV2Kind
  43880. * - BABYLON.VertexBuffer.UV3Kind
  43881. * - BABYLON.VertexBuffer.UV4Kind
  43882. * - BABYLON.VertexBuffer.UV5Kind
  43883. * - BABYLON.VertexBuffer.UV6Kind
  43884. * - BABYLON.VertexBuffer.ColorKind
  43885. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43886. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43887. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43888. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43889. *
  43890. * Returns the Mesh.
  43891. */
  43892. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  43893. if (this.sourceMesh) {
  43894. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  43895. }
  43896. return this.sourceMesh;
  43897. };
  43898. /**
  43899. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  43900. * If the mesh has no geometry, it is simply returned as it is.
  43901. * The `data` are either a numeric array either a Float32Array.
  43902. * No new underlying VertexBuffer object is created.
  43903. * 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.
  43904. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  43905. *
  43906. * Possible `kind` values :
  43907. * - BABYLON.VertexBuffer.PositionKind
  43908. * - BABYLON.VertexBuffer.UVKind
  43909. * - BABYLON.VertexBuffer.UV2Kind
  43910. * - BABYLON.VertexBuffer.UV3Kind
  43911. * - BABYLON.VertexBuffer.UV4Kind
  43912. * - BABYLON.VertexBuffer.UV5Kind
  43913. * - BABYLON.VertexBuffer.UV6Kind
  43914. * - BABYLON.VertexBuffer.ColorKind
  43915. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43916. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43917. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43918. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43919. *
  43920. * Returns the Mesh.
  43921. */
  43922. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  43923. if (this.sourceMesh) {
  43924. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  43925. }
  43926. return this.sourceMesh;
  43927. };
  43928. /**
  43929. * Sets the mesh indices.
  43930. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  43931. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  43932. * This method creates a new index buffer each call.
  43933. * Returns the Mesh.
  43934. */
  43935. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  43936. if (this.sourceMesh) {
  43937. this.sourceMesh.setIndices(indices, totalVertices);
  43938. }
  43939. return this.sourceMesh;
  43940. };
  43941. /**
  43942. * Boolean : True if the mesh owns the requested kind of data.
  43943. */
  43944. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  43945. return this._sourceMesh.isVerticesDataPresent(kind);
  43946. };
  43947. /**
  43948. * Returns an array of indices (IndicesArray).
  43949. */
  43950. InstancedMesh.prototype.getIndices = function () {
  43951. return this._sourceMesh.getIndices();
  43952. };
  43953. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  43954. get: function () {
  43955. return this._sourceMesh._positions;
  43956. },
  43957. enumerable: true,
  43958. configurable: true
  43959. });
  43960. /**
  43961. * Sets a new updated BoundingInfo to the mesh.
  43962. * Returns the mesh.
  43963. */
  43964. InstancedMesh.prototype.refreshBoundingInfo = function () {
  43965. var meshBB = this._sourceMesh.getBoundingInfo();
  43966. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  43967. this._updateBoundingInfo();
  43968. return this;
  43969. };
  43970. InstancedMesh.prototype._preActivate = function () {
  43971. if (this._currentLOD) {
  43972. this._currentLOD._preActivate();
  43973. }
  43974. return this;
  43975. };
  43976. InstancedMesh.prototype._activate = function (renderId) {
  43977. if (this._currentLOD) {
  43978. this._currentLOD._registerInstanceForRenderId(this, renderId);
  43979. }
  43980. return this;
  43981. };
  43982. /**
  43983. * Returns the current associated LOD AbstractMesh.
  43984. */
  43985. InstancedMesh.prototype.getLOD = function (camera) {
  43986. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  43987. if (this._currentLOD === this.sourceMesh) {
  43988. return this;
  43989. }
  43990. return this._currentLOD;
  43991. };
  43992. InstancedMesh.prototype._syncSubMeshes = function () {
  43993. this.releaseSubMeshes();
  43994. if (this._sourceMesh.subMeshes) {
  43995. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  43996. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  43997. }
  43998. }
  43999. return this;
  44000. };
  44001. InstancedMesh.prototype._generatePointsArray = function () {
  44002. return this._sourceMesh._generatePointsArray();
  44003. };
  44004. /**
  44005. * Creates a new InstancedMesh from the current mesh.
  44006. * - name (string) : the cloned mesh name
  44007. * - newParent (optional Node) : the optional Node to parent the clone to.
  44008. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  44009. *
  44010. * Returns the clone.
  44011. */
  44012. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  44013. var result = this._sourceMesh.createInstance(name);
  44014. // Deep copy
  44015. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  44016. // Bounding info
  44017. this.refreshBoundingInfo();
  44018. // Parent
  44019. if (newParent) {
  44020. result.parent = newParent;
  44021. }
  44022. if (!doNotCloneChildren) {
  44023. // Children
  44024. for (var index = 0; index < this.getScene().meshes.length; index++) {
  44025. var mesh = this.getScene().meshes[index];
  44026. if (mesh.parent === this) {
  44027. mesh.clone(mesh.name, result);
  44028. }
  44029. }
  44030. }
  44031. result.computeWorldMatrix(true);
  44032. return result;
  44033. };
  44034. /**
  44035. * Disposes the InstancedMesh.
  44036. * Returns nothing.
  44037. */
  44038. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  44039. // Remove from mesh
  44040. var index = this._sourceMesh.instances.indexOf(this);
  44041. this._sourceMesh.instances.splice(index, 1);
  44042. _super.prototype.dispose.call(this, doNotRecurse);
  44043. };
  44044. return InstancedMesh;
  44045. }(BABYLON.AbstractMesh));
  44046. BABYLON.InstancedMesh = InstancedMesh;
  44047. })(BABYLON || (BABYLON = {}));
  44048. //# sourceMappingURL=babylon.instancedMesh.js.map
  44049. /// <reference path="babylon.mesh.ts" />
  44050. var BABYLON;
  44051. (function (BABYLON) {
  44052. var LinesMesh = (function (_super) {
  44053. __extends(LinesMesh, _super);
  44054. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  44055. if (parent === void 0) { parent = null; }
  44056. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  44057. _this.useVertexColor = useVertexColor;
  44058. _this.color = new BABYLON.Color3(1, 1, 1);
  44059. _this.alpha = 1;
  44060. if (source) {
  44061. _this.color = source.color.clone();
  44062. _this.alpha = source.alpha;
  44063. _this.useVertexColor = source.useVertexColor;
  44064. }
  44065. _this._intersectionThreshold = 0.1;
  44066. var options = {
  44067. attributes: [BABYLON.VertexBuffer.PositionKind],
  44068. uniforms: ["world", "viewProjection"],
  44069. needAlphaBlending: false,
  44070. };
  44071. if (!useVertexColor) {
  44072. options.uniforms.push("color");
  44073. options.needAlphaBlending = true;
  44074. }
  44075. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  44076. return _this;
  44077. }
  44078. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  44079. /**
  44080. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  44081. * This margin is expressed in world space coordinates, so its value may vary.
  44082. * Default value is 0.1
  44083. * @returns the intersection Threshold value.
  44084. */
  44085. get: function () {
  44086. return this._intersectionThreshold;
  44087. },
  44088. /**
  44089. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  44090. * This margin is expressed in world space coordinates, so its value may vary.
  44091. * @param value the new threshold to apply
  44092. */
  44093. set: function (value) {
  44094. if (this._intersectionThreshold === value) {
  44095. return;
  44096. }
  44097. this._intersectionThreshold = value;
  44098. if (this.geometry) {
  44099. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  44100. }
  44101. },
  44102. enumerable: true,
  44103. configurable: true
  44104. });
  44105. /**
  44106. * Returns the string "LineMesh"
  44107. */
  44108. LinesMesh.prototype.getClassName = function () {
  44109. return "LinesMesh";
  44110. };
  44111. Object.defineProperty(LinesMesh.prototype, "material", {
  44112. get: function () {
  44113. return this._colorShader;
  44114. },
  44115. enumerable: true,
  44116. configurable: true
  44117. });
  44118. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  44119. get: function () {
  44120. return false;
  44121. },
  44122. enumerable: true,
  44123. configurable: true
  44124. });
  44125. LinesMesh.prototype.createInstance = function (name) {
  44126. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  44127. return null;
  44128. };
  44129. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  44130. // VBOs
  44131. this._geometry._bind(this._colorShader.getEffect());
  44132. // Color
  44133. if (!this.useVertexColor) {
  44134. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  44135. }
  44136. return this;
  44137. };
  44138. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  44139. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  44140. return this;
  44141. }
  44142. var engine = this.getScene().getEngine();
  44143. // Draw order
  44144. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  44145. return this;
  44146. };
  44147. LinesMesh.prototype.dispose = function (doNotRecurse) {
  44148. this._colorShader.dispose();
  44149. _super.prototype.dispose.call(this, doNotRecurse);
  44150. };
  44151. /**
  44152. * Returns a new LineMesh object cloned from the current one.
  44153. */
  44154. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  44155. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  44156. };
  44157. return LinesMesh;
  44158. }(BABYLON.Mesh));
  44159. BABYLON.LinesMesh = LinesMesh;
  44160. })(BABYLON || (BABYLON = {}));
  44161. //# sourceMappingURL=babylon.linesMesh.js.map
  44162. var BABYLON;
  44163. (function (BABYLON) {
  44164. var StandardMaterialDefines = (function (_super) {
  44165. __extends(StandardMaterialDefines, _super);
  44166. function StandardMaterialDefines() {
  44167. var _this = _super.call(this) || this;
  44168. _this.MAINUV1 = false;
  44169. _this.MAINUV2 = false;
  44170. _this.DIFFUSE = false;
  44171. _this.DIFFUSEDIRECTUV = 0;
  44172. _this.AMBIENT = false;
  44173. _this.AMBIENTDIRECTUV = 0;
  44174. _this.OPACITY = false;
  44175. _this.OPACITYDIRECTUV = 0;
  44176. _this.OPACITYRGB = false;
  44177. _this.REFLECTION = false;
  44178. _this.EMISSIVE = false;
  44179. _this.EMISSIVEDIRECTUV = 0;
  44180. _this.SPECULAR = false;
  44181. _this.SPECULARDIRECTUV = 0;
  44182. _this.BUMP = false;
  44183. _this.BUMPDIRECTUV = 0;
  44184. _this.PARALLAX = false;
  44185. _this.PARALLAXOCCLUSION = false;
  44186. _this.SPECULAROVERALPHA = false;
  44187. _this.CLIPPLANE = false;
  44188. _this.ALPHATEST = false;
  44189. _this.ALPHAFROMDIFFUSE = false;
  44190. _this.POINTSIZE = false;
  44191. _this.FOG = false;
  44192. _this.SPECULARTERM = false;
  44193. _this.DIFFUSEFRESNEL = false;
  44194. _this.OPACITYFRESNEL = false;
  44195. _this.REFLECTIONFRESNEL = false;
  44196. _this.REFRACTIONFRESNEL = false;
  44197. _this.EMISSIVEFRESNEL = false;
  44198. _this.FRESNEL = false;
  44199. _this.NORMAL = false;
  44200. _this.UV1 = false;
  44201. _this.UV2 = false;
  44202. _this.VERTEXCOLOR = false;
  44203. _this.VERTEXALPHA = false;
  44204. _this.NUM_BONE_INFLUENCERS = 0;
  44205. _this.BonesPerMesh = 0;
  44206. _this.INSTANCES = false;
  44207. _this.GLOSSINESS = false;
  44208. _this.ROUGHNESS = false;
  44209. _this.EMISSIVEASILLUMINATION = false;
  44210. _this.LINKEMISSIVEWITHDIFFUSE = false;
  44211. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  44212. _this.LIGHTMAP = false;
  44213. _this.LIGHTMAPDIRECTUV = 0;
  44214. _this.USELIGHTMAPASSHADOWMAP = false;
  44215. _this.REFLECTIONMAP_3D = false;
  44216. _this.REFLECTIONMAP_SPHERICAL = false;
  44217. _this.REFLECTIONMAP_PLANAR = false;
  44218. _this.REFLECTIONMAP_CUBIC = false;
  44219. _this.REFLECTIONMAP_PROJECTION = false;
  44220. _this.REFLECTIONMAP_SKYBOX = false;
  44221. _this.REFLECTIONMAP_EXPLICIT = false;
  44222. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44223. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44224. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44225. _this.INVERTCUBICMAP = false;
  44226. _this.LOGARITHMICDEPTH = false;
  44227. _this.REFRACTION = false;
  44228. _this.REFRACTIONMAP_3D = false;
  44229. _this.REFLECTIONOVERALPHA = false;
  44230. _this.TWOSIDEDLIGHTING = false;
  44231. _this.SHADOWFLOAT = false;
  44232. _this.MORPHTARGETS = false;
  44233. _this.MORPHTARGETS_NORMAL = false;
  44234. _this.MORPHTARGETS_TANGENT = false;
  44235. _this.NUM_MORPH_INFLUENCERS = 0;
  44236. _this.USERIGHTHANDEDSYSTEM = false;
  44237. _this.IMAGEPROCESSING = false;
  44238. _this.VIGNETTE = false;
  44239. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44240. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44241. _this.TONEMAPPING = false;
  44242. _this.CONTRAST = false;
  44243. _this.COLORCURVES = false;
  44244. _this.COLORGRADING = false;
  44245. _this.SAMPLER3DGREENDEPTH = false;
  44246. _this.SAMPLER3DBGRMAP = false;
  44247. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44248. _this.EXPOSURE = false;
  44249. _this.rebuild();
  44250. return _this;
  44251. }
  44252. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  44253. var modes = [
  44254. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  44255. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  44256. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  44257. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  44258. ];
  44259. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  44260. var mode = modes_1[_i];
  44261. this[mode] = (mode === modeToEnable);
  44262. }
  44263. };
  44264. return StandardMaterialDefines;
  44265. }(BABYLON.MaterialDefines));
  44266. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  44267. var StandardMaterial = (function (_super) {
  44268. __extends(StandardMaterial, _super);
  44269. function StandardMaterial(name, scene) {
  44270. var _this = _super.call(this, name, scene) || this;
  44271. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44272. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  44273. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  44274. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44275. _this.specularPower = 64;
  44276. _this._useAlphaFromDiffuseTexture = false;
  44277. _this._useEmissiveAsIllumination = false;
  44278. _this._linkEmissiveWithDiffuse = false;
  44279. _this._useSpecularOverAlpha = false;
  44280. _this._useReflectionOverAlpha = false;
  44281. _this._disableLighting = false;
  44282. _this._useParallax = false;
  44283. _this._useParallaxOcclusion = false;
  44284. _this.parallaxScaleBias = 0.05;
  44285. _this._roughness = 0;
  44286. _this.indexOfRefraction = 0.98;
  44287. _this.invertRefractionY = true;
  44288. _this._useLightmapAsShadowmap = false;
  44289. _this._useReflectionFresnelFromSpecular = false;
  44290. _this._useGlossinessFromSpecularMapAlpha = false;
  44291. _this._maxSimultaneousLights = 4;
  44292. /**
  44293. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44294. */
  44295. _this._invertNormalMapX = false;
  44296. /**
  44297. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44298. */
  44299. _this._invertNormalMapY = false;
  44300. /**
  44301. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44302. */
  44303. _this._twoSidedLighting = false;
  44304. _this._renderTargets = new BABYLON.SmartArray(16);
  44305. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  44306. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44307. // Setup the default processing configuration to the scene.
  44308. _this._attachImageProcessingConfiguration(null);
  44309. _this.getRenderTargetTextures = function () {
  44310. _this._renderTargets.reset();
  44311. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44312. _this._renderTargets.push(_this._reflectionTexture);
  44313. }
  44314. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44315. _this._renderTargets.push(_this._refractionTexture);
  44316. }
  44317. return _this._renderTargets;
  44318. };
  44319. return _this;
  44320. }
  44321. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  44322. /**
  44323. * Gets the image processing configuration used either in this material.
  44324. */
  44325. get: function () {
  44326. return this._imageProcessingConfiguration;
  44327. },
  44328. /**
  44329. * Sets the Default image processing configuration used either in the this material.
  44330. *
  44331. * If sets to null, the scene one is in use.
  44332. */
  44333. set: function (value) {
  44334. this._attachImageProcessingConfiguration(value);
  44335. // Ensure the effect will be rebuilt.
  44336. this._markAllSubMeshesAsTexturesDirty();
  44337. },
  44338. enumerable: true,
  44339. configurable: true
  44340. });
  44341. /**
  44342. * Attaches a new image processing configuration to the Standard Material.
  44343. * @param configuration
  44344. */
  44345. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44346. var _this = this;
  44347. if (configuration === this._imageProcessingConfiguration) {
  44348. return;
  44349. }
  44350. // Detaches observer.
  44351. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44352. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44353. }
  44354. // Pick the scene configuration if needed.
  44355. if (!configuration) {
  44356. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44357. }
  44358. else {
  44359. this._imageProcessingConfiguration = configuration;
  44360. }
  44361. // Attaches observer.
  44362. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44363. _this._markAllSubMeshesAsImageProcessingDirty();
  44364. });
  44365. };
  44366. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  44367. /**
  44368. * Gets wether the color curves effect is enabled.
  44369. */
  44370. get: function () {
  44371. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44372. },
  44373. /**
  44374. * Sets wether the color curves effect is enabled.
  44375. */
  44376. set: function (value) {
  44377. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44378. },
  44379. enumerable: true,
  44380. configurable: true
  44381. });
  44382. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  44383. /**
  44384. * Gets wether the color grading effect is enabled.
  44385. */
  44386. get: function () {
  44387. return this.imageProcessingConfiguration.colorGradingEnabled;
  44388. },
  44389. /**
  44390. * Gets wether the color grading effect is enabled.
  44391. */
  44392. set: function (value) {
  44393. this.imageProcessingConfiguration.colorGradingEnabled = value;
  44394. },
  44395. enumerable: true,
  44396. configurable: true
  44397. });
  44398. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  44399. /**
  44400. * Gets wether tonemapping is enabled or not.
  44401. */
  44402. get: function () {
  44403. return this._imageProcessingConfiguration.toneMappingEnabled;
  44404. },
  44405. /**
  44406. * Sets wether tonemapping is enabled or not
  44407. */
  44408. set: function (value) {
  44409. this._imageProcessingConfiguration.toneMappingEnabled = value;
  44410. },
  44411. enumerable: true,
  44412. configurable: true
  44413. });
  44414. ;
  44415. ;
  44416. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  44417. /**
  44418. * The camera exposure used on this material.
  44419. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44420. * This corresponds to a photographic exposure.
  44421. */
  44422. get: function () {
  44423. return this._imageProcessingConfiguration.exposure;
  44424. },
  44425. /**
  44426. * The camera exposure used on this material.
  44427. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44428. * This corresponds to a photographic exposure.
  44429. */
  44430. set: function (value) {
  44431. this._imageProcessingConfiguration.exposure = value;
  44432. },
  44433. enumerable: true,
  44434. configurable: true
  44435. });
  44436. ;
  44437. ;
  44438. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  44439. /**
  44440. * Gets The camera contrast used on this material.
  44441. */
  44442. get: function () {
  44443. return this._imageProcessingConfiguration.contrast;
  44444. },
  44445. /**
  44446. * Sets The camera contrast used on this material.
  44447. */
  44448. set: function (value) {
  44449. this._imageProcessingConfiguration.contrast = value;
  44450. },
  44451. enumerable: true,
  44452. configurable: true
  44453. });
  44454. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  44455. /**
  44456. * Gets the Color Grading 2D Lookup Texture.
  44457. */
  44458. get: function () {
  44459. return this._imageProcessingConfiguration.colorGradingTexture;
  44460. },
  44461. /**
  44462. * Sets the Color Grading 2D Lookup Texture.
  44463. */
  44464. set: function (value) {
  44465. this._imageProcessingConfiguration.colorGradingTexture = value;
  44466. },
  44467. enumerable: true,
  44468. configurable: true
  44469. });
  44470. StandardMaterial.prototype.getClassName = function () {
  44471. return "StandardMaterial";
  44472. };
  44473. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  44474. get: function () {
  44475. return this._useLogarithmicDepth;
  44476. },
  44477. set: function (value) {
  44478. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44479. this._markAllSubMeshesAsMiscDirty();
  44480. },
  44481. enumerable: true,
  44482. configurable: true
  44483. });
  44484. StandardMaterial.prototype.needAlphaBlending = function () {
  44485. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  44486. };
  44487. StandardMaterial.prototype.needAlphaTesting = function () {
  44488. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  44489. };
  44490. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  44491. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  44492. };
  44493. StandardMaterial.prototype.getAlphaTestTexture = function () {
  44494. return this._diffuseTexture;
  44495. };
  44496. /**
  44497. * Child classes can use it to update shaders
  44498. */
  44499. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44500. if (this.isFrozen) {
  44501. if (this._wasPreviouslyReady && subMesh.effect) {
  44502. return true;
  44503. }
  44504. }
  44505. if (!subMesh._materialDefines) {
  44506. subMesh._materialDefines = new StandardMaterialDefines();
  44507. }
  44508. var scene = this.getScene();
  44509. var defines = subMesh._materialDefines;
  44510. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44511. if (defines._renderId === scene.getRenderId()) {
  44512. return true;
  44513. }
  44514. }
  44515. var engine = scene.getEngine();
  44516. // Lights
  44517. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44518. // Textures
  44519. if (defines._areTexturesDirty) {
  44520. defines._needUVs = false;
  44521. defines.MAINUV1 = false;
  44522. defines.MAINUV2 = false;
  44523. if (scene.texturesEnabled) {
  44524. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44525. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  44526. return false;
  44527. }
  44528. else {
  44529. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  44530. }
  44531. }
  44532. else {
  44533. defines.DIFFUSE = false;
  44534. }
  44535. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44536. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44537. return false;
  44538. }
  44539. else {
  44540. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44541. }
  44542. }
  44543. else {
  44544. defines.AMBIENT = false;
  44545. }
  44546. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44547. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44548. return false;
  44549. }
  44550. else {
  44551. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44552. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44553. }
  44554. }
  44555. else {
  44556. defines.OPACITY = false;
  44557. }
  44558. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44559. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  44560. return false;
  44561. }
  44562. else {
  44563. defines._needNormals = true;
  44564. defines.REFLECTION = true;
  44565. defines.ROUGHNESS = (this._roughness > 0);
  44566. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  44567. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  44568. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  44569. switch (this._reflectionTexture.coordinatesMode) {
  44570. case BABYLON.Texture.CUBIC_MODE:
  44571. case BABYLON.Texture.INVCUBIC_MODE:
  44572. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  44573. break;
  44574. case BABYLON.Texture.EXPLICIT_MODE:
  44575. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  44576. break;
  44577. case BABYLON.Texture.PLANAR_MODE:
  44578. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  44579. break;
  44580. case BABYLON.Texture.PROJECTION_MODE:
  44581. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  44582. break;
  44583. case BABYLON.Texture.SKYBOX_MODE:
  44584. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  44585. break;
  44586. case BABYLON.Texture.SPHERICAL_MODE:
  44587. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  44588. break;
  44589. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44590. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  44591. break;
  44592. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44593. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  44594. break;
  44595. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44596. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  44597. break;
  44598. }
  44599. }
  44600. }
  44601. else {
  44602. defines.REFLECTION = false;
  44603. }
  44604. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44605. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44606. return false;
  44607. }
  44608. else {
  44609. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44610. }
  44611. }
  44612. else {
  44613. defines.EMISSIVE = false;
  44614. }
  44615. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44616. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44617. return false;
  44618. }
  44619. else {
  44620. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44621. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44622. }
  44623. }
  44624. else {
  44625. defines.LIGHTMAP = false;
  44626. }
  44627. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44628. if (!this._specularTexture.isReadyOrNotBlocking()) {
  44629. return false;
  44630. }
  44631. else {
  44632. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  44633. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  44634. }
  44635. }
  44636. else {
  44637. defines.SPECULAR = false;
  44638. }
  44639. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  44640. // Bump texure can not be not blocking.
  44641. if (!this._bumpTexture.isReady()) {
  44642. return false;
  44643. }
  44644. else {
  44645. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44646. defines.PARALLAX = this._useParallax;
  44647. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  44648. }
  44649. }
  44650. else {
  44651. defines.BUMP = false;
  44652. }
  44653. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44654. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  44655. return false;
  44656. }
  44657. else {
  44658. defines._needUVs = true;
  44659. defines.REFRACTION = true;
  44660. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  44661. }
  44662. }
  44663. else {
  44664. defines.REFRACTION = false;
  44665. }
  44666. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  44667. }
  44668. else {
  44669. defines.DIFFUSE = false;
  44670. defines.AMBIENT = false;
  44671. defines.OPACITY = false;
  44672. defines.REFLECTION = false;
  44673. defines.EMISSIVE = false;
  44674. defines.LIGHTMAP = false;
  44675. defines.BUMP = false;
  44676. defines.REFRACTION = false;
  44677. }
  44678. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  44679. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  44680. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  44681. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44682. }
  44683. if (defines._areImageProcessingDirty) {
  44684. if (!this._imageProcessingConfiguration.isReady()) {
  44685. return false;
  44686. }
  44687. this._imageProcessingConfiguration.prepareDefines(defines);
  44688. }
  44689. if (defines._areFresnelDirty) {
  44690. if (StandardMaterial.FresnelEnabled) {
  44691. // Fresnel
  44692. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  44693. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  44694. this._reflectionFresnelParameters) {
  44695. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  44696. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  44697. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  44698. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  44699. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  44700. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  44701. defines._needNormals = true;
  44702. defines.FRESNEL = true;
  44703. }
  44704. }
  44705. else {
  44706. defines.FRESNEL = false;
  44707. }
  44708. }
  44709. // Misc.
  44710. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  44711. // Attribs
  44712. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  44713. // Values that need to be evaluated on every frame
  44714. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  44715. // Get correct effect
  44716. if (defines.isDirty) {
  44717. defines.markAsProcessed();
  44718. scene.resetCachedMaterial();
  44719. // Fallbacks
  44720. var fallbacks = new BABYLON.EffectFallbacks();
  44721. if (defines.REFLECTION) {
  44722. fallbacks.addFallback(0, "REFLECTION");
  44723. }
  44724. if (defines.SPECULAR) {
  44725. fallbacks.addFallback(0, "SPECULAR");
  44726. }
  44727. if (defines.BUMP) {
  44728. fallbacks.addFallback(0, "BUMP");
  44729. }
  44730. if (defines.PARALLAX) {
  44731. fallbacks.addFallback(1, "PARALLAX");
  44732. }
  44733. if (defines.PARALLAXOCCLUSION) {
  44734. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44735. }
  44736. if (defines.SPECULAROVERALPHA) {
  44737. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44738. }
  44739. if (defines.FOG) {
  44740. fallbacks.addFallback(1, "FOG");
  44741. }
  44742. if (defines.POINTSIZE) {
  44743. fallbacks.addFallback(0, "POINTSIZE");
  44744. }
  44745. if (defines.LOGARITHMICDEPTH) {
  44746. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44747. }
  44748. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  44749. if (defines.SPECULARTERM) {
  44750. fallbacks.addFallback(0, "SPECULARTERM");
  44751. }
  44752. if (defines.DIFFUSEFRESNEL) {
  44753. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  44754. }
  44755. if (defines.OPACITYFRESNEL) {
  44756. fallbacks.addFallback(2, "OPACITYFRESNEL");
  44757. }
  44758. if (defines.REFLECTIONFRESNEL) {
  44759. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  44760. }
  44761. if (defines.EMISSIVEFRESNEL) {
  44762. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  44763. }
  44764. if (defines.FRESNEL) {
  44765. fallbacks.addFallback(4, "FRESNEL");
  44766. }
  44767. //Attributes
  44768. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44769. if (defines.NORMAL) {
  44770. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44771. }
  44772. if (defines.UV1) {
  44773. attribs.push(BABYLON.VertexBuffer.UVKind);
  44774. }
  44775. if (defines.UV2) {
  44776. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44777. }
  44778. if (defines.VERTEXCOLOR) {
  44779. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44780. }
  44781. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44782. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44783. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44784. var shaderName = "default";
  44785. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  44786. "vFogInfos", "vFogColor", "pointSize",
  44787. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44788. "mBones",
  44789. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44790. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  44791. "logarithmicDepthConstant", "vNormalReoderParams"
  44792. ];
  44793. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  44794. var uniformBuffers = ["Material", "Scene"];
  44795. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44796. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44797. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44798. uniformsNames: uniforms,
  44799. uniformBuffersNames: uniformBuffers,
  44800. samplers: samplers,
  44801. defines: defines,
  44802. maxSimultaneousLights: this._maxSimultaneousLights
  44803. });
  44804. if (this.customShaderNameResolve) {
  44805. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  44806. }
  44807. var join = defines.toString();
  44808. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  44809. attributes: attribs,
  44810. uniformsNames: uniforms,
  44811. uniformBuffersNames: uniformBuffers,
  44812. samplers: samplers,
  44813. defines: join,
  44814. fallbacks: fallbacks,
  44815. onCompiled: this.onCompiled,
  44816. onError: this.onError,
  44817. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44818. }, engine), defines);
  44819. this.buildUniformLayout();
  44820. }
  44821. if (!subMesh.effect.isReady()) {
  44822. return false;
  44823. }
  44824. defines._renderId = scene.getRenderId();
  44825. this._wasPreviouslyReady = true;
  44826. return true;
  44827. };
  44828. StandardMaterial.prototype.buildUniformLayout = function () {
  44829. // Order is important !
  44830. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  44831. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  44832. this._uniformBuffer.addUniform("opacityParts", 4);
  44833. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  44834. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  44835. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  44836. this._uniformBuffer.addUniform("refractionRightColor", 4);
  44837. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  44838. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  44839. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  44840. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  44841. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44842. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44843. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44844. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44845. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  44846. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44847. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  44848. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44849. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44850. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44851. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44852. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44853. this._uniformBuffer.addUniform("specularMatrix", 16);
  44854. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44855. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  44856. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44857. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44858. this._uniformBuffer.addUniform("vSpecularColor", 4);
  44859. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44860. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  44861. this._uniformBuffer.addUniform("pointSize", 1);
  44862. this._uniformBuffer.create();
  44863. };
  44864. StandardMaterial.prototype.unbind = function () {
  44865. if (this._activeEffect) {
  44866. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44867. this._activeEffect.setTexture("reflection2DSampler", null);
  44868. }
  44869. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44870. this._activeEffect.setTexture("refraction2DSampler", null);
  44871. }
  44872. }
  44873. _super.prototype.unbind.call(this);
  44874. };
  44875. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44876. var scene = this.getScene();
  44877. var defines = subMesh._materialDefines;
  44878. if (!defines) {
  44879. return;
  44880. }
  44881. var effect = subMesh.effect;
  44882. this._activeEffect = effect;
  44883. // Matrices
  44884. this.bindOnlyWorldMatrix(world);
  44885. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44886. // Bones
  44887. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  44888. if (mustRebind) {
  44889. this._uniformBuffer.bindToEffect(effect, "Material");
  44890. this.bindViewProjection(effect);
  44891. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44892. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  44893. // Fresnel
  44894. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  44895. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  44896. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  44897. }
  44898. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44899. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44900. }
  44901. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  44902. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  44903. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  44904. }
  44905. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  44906. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  44907. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  44908. }
  44909. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44910. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44911. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44912. }
  44913. }
  44914. // Textures
  44915. if (scene.texturesEnabled) {
  44916. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44917. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  44918. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44919. }
  44920. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44921. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44922. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44923. }
  44924. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44925. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44926. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44927. }
  44928. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44929. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44930. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44931. }
  44932. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44933. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44934. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44935. }
  44936. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44937. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44938. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44939. }
  44940. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44941. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44942. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44943. }
  44944. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44945. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44946. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44947. if (scene._mirroredCameraPosition) {
  44948. this._uniformBuffer.updateFloat4("vNormalReoderParams", this.invertNormalMapX ? 0 : 1.0, this.invertNormalMapX ? 1.0 : -1.0, this.invertNormalMapY ? 0 : 1.0, this.invertNormalMapY ? 1.0 : -1.0);
  44949. }
  44950. else {
  44951. this._uniformBuffer.updateFloat4("vNormalReoderParams", this.invertNormalMapX ? 1.0 : 0, this.invertNormalMapX ? -1.0 : 1.0, this.invertNormalMapY ? 1.0 : 0, this.invertNormalMapY ? -1.0 : 1.0);
  44952. }
  44953. }
  44954. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44955. var depth = 1.0;
  44956. if (!this._refractionTexture.isCube) {
  44957. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44958. if (this._refractionTexture.depth) {
  44959. depth = this._refractionTexture.depth;
  44960. }
  44961. }
  44962. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44963. }
  44964. }
  44965. // Point size
  44966. if (this.pointsCloud) {
  44967. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44968. }
  44969. if (defines.SPECULARTERM) {
  44970. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44971. }
  44972. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44973. // Diffuse
  44974. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44975. }
  44976. // Textures
  44977. if (scene.texturesEnabled) {
  44978. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44979. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44980. }
  44981. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44982. effect.setTexture("ambientSampler", this._ambientTexture);
  44983. }
  44984. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44985. effect.setTexture("opacitySampler", this._opacityTexture);
  44986. }
  44987. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44988. if (this._reflectionTexture.isCube) {
  44989. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44990. }
  44991. else {
  44992. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44993. }
  44994. }
  44995. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44996. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44997. }
  44998. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44999. effect.setTexture("lightmapSampler", this._lightmapTexture);
  45000. }
  45001. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  45002. effect.setTexture("specularSampler", this._specularTexture);
  45003. }
  45004. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  45005. effect.setTexture("bumpSampler", this._bumpTexture);
  45006. }
  45007. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  45008. var depth = 1.0;
  45009. if (this._refractionTexture.isCube) {
  45010. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  45011. }
  45012. else {
  45013. effect.setTexture("refraction2DSampler", this._refractionTexture);
  45014. }
  45015. }
  45016. }
  45017. // Clip plane
  45018. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  45019. // Colors
  45020. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  45021. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45022. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45023. }
  45024. if (mustRebind || !this.isFrozen) {
  45025. // Lights
  45026. if (scene.lightsEnabled && !this._disableLighting) {
  45027. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  45028. }
  45029. // View
  45030. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  45031. this.bindView(effect);
  45032. }
  45033. // Fog
  45034. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  45035. // Morph targets
  45036. if (defines.NUM_MORPH_INFLUENCERS) {
  45037. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  45038. }
  45039. // Log. depth
  45040. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  45041. // image processing
  45042. this._imageProcessingConfiguration.bind(this._activeEffect);
  45043. }
  45044. this._uniformBuffer.update();
  45045. this._afterBind(mesh, this._activeEffect);
  45046. };
  45047. StandardMaterial.prototype.getAnimatables = function () {
  45048. var results = [];
  45049. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  45050. results.push(this._diffuseTexture);
  45051. }
  45052. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45053. results.push(this._ambientTexture);
  45054. }
  45055. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45056. results.push(this._opacityTexture);
  45057. }
  45058. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45059. results.push(this._reflectionTexture);
  45060. }
  45061. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45062. results.push(this._emissiveTexture);
  45063. }
  45064. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  45065. results.push(this._specularTexture);
  45066. }
  45067. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45068. results.push(this._bumpTexture);
  45069. }
  45070. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45071. results.push(this._lightmapTexture);
  45072. }
  45073. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45074. results.push(this._refractionTexture);
  45075. }
  45076. return results;
  45077. };
  45078. StandardMaterial.prototype.getActiveTextures = function () {
  45079. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45080. if (this._diffuseTexture) {
  45081. activeTextures.push(this._diffuseTexture);
  45082. }
  45083. if (this._ambientTexture) {
  45084. activeTextures.push(this._ambientTexture);
  45085. }
  45086. if (this._opacityTexture) {
  45087. activeTextures.push(this._opacityTexture);
  45088. }
  45089. if (this._reflectionTexture) {
  45090. activeTextures.push(this._reflectionTexture);
  45091. }
  45092. if (this._emissiveTexture) {
  45093. activeTextures.push(this._emissiveTexture);
  45094. }
  45095. if (this._specularTexture) {
  45096. activeTextures.push(this._specularTexture);
  45097. }
  45098. if (this._bumpTexture) {
  45099. activeTextures.push(this._bumpTexture);
  45100. }
  45101. if (this._lightmapTexture) {
  45102. activeTextures.push(this._lightmapTexture);
  45103. }
  45104. if (this._refractionTexture) {
  45105. activeTextures.push(this._refractionTexture);
  45106. }
  45107. return activeTextures;
  45108. };
  45109. StandardMaterial.prototype.hasTexture = function (texture) {
  45110. if (_super.prototype.hasTexture.call(this, texture)) {
  45111. return true;
  45112. }
  45113. if (this._diffuseTexture === texture) {
  45114. return true;
  45115. }
  45116. if (this._ambientTexture === texture) {
  45117. return true;
  45118. }
  45119. if (this._opacityTexture === texture) {
  45120. return true;
  45121. }
  45122. if (this._reflectionTexture === texture) {
  45123. return true;
  45124. }
  45125. if (this._emissiveTexture === texture) {
  45126. return true;
  45127. }
  45128. if (this._specularTexture === texture) {
  45129. return true;
  45130. }
  45131. if (this._bumpTexture === texture) {
  45132. return true;
  45133. }
  45134. if (this._lightmapTexture === texture) {
  45135. return true;
  45136. }
  45137. if (this._refractionTexture === texture) {
  45138. return true;
  45139. }
  45140. return false;
  45141. };
  45142. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45143. if (forceDisposeTextures) {
  45144. if (this._diffuseTexture) {
  45145. this._diffuseTexture.dispose();
  45146. }
  45147. if (this._ambientTexture) {
  45148. this._ambientTexture.dispose();
  45149. }
  45150. if (this._opacityTexture) {
  45151. this._opacityTexture.dispose();
  45152. }
  45153. if (this._reflectionTexture) {
  45154. this._reflectionTexture.dispose();
  45155. }
  45156. if (this._emissiveTexture) {
  45157. this._emissiveTexture.dispose();
  45158. }
  45159. if (this._specularTexture) {
  45160. this._specularTexture.dispose();
  45161. }
  45162. if (this._bumpTexture) {
  45163. this._bumpTexture.dispose();
  45164. }
  45165. if (this._lightmapTexture) {
  45166. this._lightmapTexture.dispose();
  45167. }
  45168. if (this._refractionTexture) {
  45169. this._refractionTexture.dispose();
  45170. }
  45171. }
  45172. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45173. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45174. }
  45175. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45176. };
  45177. StandardMaterial.prototype.clone = function (name) {
  45178. var _this = this;
  45179. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  45180. result.name = name;
  45181. result.id = name;
  45182. return result;
  45183. };
  45184. StandardMaterial.prototype.serialize = function () {
  45185. return BABYLON.SerializationHelper.Serialize(this);
  45186. };
  45187. // Statics
  45188. StandardMaterial.Parse = function (source, scene, rootUrl) {
  45189. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  45190. };
  45191. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  45192. get: function () {
  45193. return StandardMaterial._DiffuseTextureEnabled;
  45194. },
  45195. set: function (value) {
  45196. if (StandardMaterial._DiffuseTextureEnabled === value) {
  45197. return;
  45198. }
  45199. StandardMaterial._DiffuseTextureEnabled = value;
  45200. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45201. },
  45202. enumerable: true,
  45203. configurable: true
  45204. });
  45205. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  45206. get: function () {
  45207. return StandardMaterial._AmbientTextureEnabled;
  45208. },
  45209. set: function (value) {
  45210. if (StandardMaterial._AmbientTextureEnabled === value) {
  45211. return;
  45212. }
  45213. StandardMaterial._AmbientTextureEnabled = value;
  45214. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45215. },
  45216. enumerable: true,
  45217. configurable: true
  45218. });
  45219. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  45220. get: function () {
  45221. return StandardMaterial._OpacityTextureEnabled;
  45222. },
  45223. set: function (value) {
  45224. if (StandardMaterial._OpacityTextureEnabled === value) {
  45225. return;
  45226. }
  45227. StandardMaterial._OpacityTextureEnabled = value;
  45228. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45229. },
  45230. enumerable: true,
  45231. configurable: true
  45232. });
  45233. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  45234. get: function () {
  45235. return StandardMaterial._ReflectionTextureEnabled;
  45236. },
  45237. set: function (value) {
  45238. if (StandardMaterial._ReflectionTextureEnabled === value) {
  45239. return;
  45240. }
  45241. StandardMaterial._ReflectionTextureEnabled = value;
  45242. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45243. },
  45244. enumerable: true,
  45245. configurable: true
  45246. });
  45247. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  45248. get: function () {
  45249. return StandardMaterial._EmissiveTextureEnabled;
  45250. },
  45251. set: function (value) {
  45252. if (StandardMaterial._EmissiveTextureEnabled === value) {
  45253. return;
  45254. }
  45255. StandardMaterial._EmissiveTextureEnabled = value;
  45256. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45257. },
  45258. enumerable: true,
  45259. configurable: true
  45260. });
  45261. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  45262. get: function () {
  45263. return StandardMaterial._SpecularTextureEnabled;
  45264. },
  45265. set: function (value) {
  45266. if (StandardMaterial._SpecularTextureEnabled === value) {
  45267. return;
  45268. }
  45269. StandardMaterial._SpecularTextureEnabled = value;
  45270. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45271. },
  45272. enumerable: true,
  45273. configurable: true
  45274. });
  45275. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  45276. get: function () {
  45277. return StandardMaterial._BumpTextureEnabled;
  45278. },
  45279. set: function (value) {
  45280. if (StandardMaterial._BumpTextureEnabled === value) {
  45281. return;
  45282. }
  45283. StandardMaterial._BumpTextureEnabled = value;
  45284. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45285. },
  45286. enumerable: true,
  45287. configurable: true
  45288. });
  45289. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  45290. get: function () {
  45291. return StandardMaterial._LightmapTextureEnabled;
  45292. },
  45293. set: function (value) {
  45294. if (StandardMaterial._LightmapTextureEnabled === value) {
  45295. return;
  45296. }
  45297. StandardMaterial._LightmapTextureEnabled = value;
  45298. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45299. },
  45300. enumerable: true,
  45301. configurable: true
  45302. });
  45303. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  45304. get: function () {
  45305. return StandardMaterial._RefractionTextureEnabled;
  45306. },
  45307. set: function (value) {
  45308. if (StandardMaterial._RefractionTextureEnabled === value) {
  45309. return;
  45310. }
  45311. StandardMaterial._RefractionTextureEnabled = value;
  45312. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45313. },
  45314. enumerable: true,
  45315. configurable: true
  45316. });
  45317. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  45318. get: function () {
  45319. return StandardMaterial._ColorGradingTextureEnabled;
  45320. },
  45321. set: function (value) {
  45322. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  45323. return;
  45324. }
  45325. StandardMaterial._ColorGradingTextureEnabled = value;
  45326. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45327. },
  45328. enumerable: true,
  45329. configurable: true
  45330. });
  45331. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  45332. get: function () {
  45333. return StandardMaterial._FresnelEnabled;
  45334. },
  45335. set: function (value) {
  45336. if (StandardMaterial._FresnelEnabled === value) {
  45337. return;
  45338. }
  45339. StandardMaterial._FresnelEnabled = value;
  45340. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  45341. },
  45342. enumerable: true,
  45343. configurable: true
  45344. });
  45345. // Flags used to enable or disable a type of texture for all Standard Materials
  45346. StandardMaterial._DiffuseTextureEnabled = true;
  45347. StandardMaterial._AmbientTextureEnabled = true;
  45348. StandardMaterial._OpacityTextureEnabled = true;
  45349. StandardMaterial._ReflectionTextureEnabled = true;
  45350. StandardMaterial._EmissiveTextureEnabled = true;
  45351. StandardMaterial._SpecularTextureEnabled = true;
  45352. StandardMaterial._BumpTextureEnabled = true;
  45353. StandardMaterial._LightmapTextureEnabled = true;
  45354. StandardMaterial._RefractionTextureEnabled = true;
  45355. StandardMaterial._ColorGradingTextureEnabled = true;
  45356. StandardMaterial._FresnelEnabled = true;
  45357. __decorate([
  45358. BABYLON.serializeAsTexture("diffuseTexture")
  45359. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  45360. __decorate([
  45361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45362. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  45363. __decorate([
  45364. BABYLON.serializeAsTexture("ambientTexture")
  45365. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  45366. __decorate([
  45367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45368. ], StandardMaterial.prototype, "ambientTexture", void 0);
  45369. __decorate([
  45370. BABYLON.serializeAsTexture("opacityTexture")
  45371. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  45372. __decorate([
  45373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45374. ], StandardMaterial.prototype, "opacityTexture", void 0);
  45375. __decorate([
  45376. BABYLON.serializeAsTexture("reflectionTexture")
  45377. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  45378. __decorate([
  45379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45380. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  45381. __decorate([
  45382. BABYLON.serializeAsTexture("emissiveTexture")
  45383. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  45384. __decorate([
  45385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45386. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  45387. __decorate([
  45388. BABYLON.serializeAsTexture("specularTexture")
  45389. ], StandardMaterial.prototype, "_specularTexture", void 0);
  45390. __decorate([
  45391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45392. ], StandardMaterial.prototype, "specularTexture", void 0);
  45393. __decorate([
  45394. BABYLON.serializeAsTexture("bumpTexture")
  45395. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  45396. __decorate([
  45397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45398. ], StandardMaterial.prototype, "bumpTexture", void 0);
  45399. __decorate([
  45400. BABYLON.serializeAsTexture("lightmapTexture")
  45401. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  45402. __decorate([
  45403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45404. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  45405. __decorate([
  45406. BABYLON.serializeAsTexture("refractionTexture")
  45407. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  45408. __decorate([
  45409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45410. ], StandardMaterial.prototype, "refractionTexture", void 0);
  45411. __decorate([
  45412. BABYLON.serializeAsColor3("ambient")
  45413. ], StandardMaterial.prototype, "ambientColor", void 0);
  45414. __decorate([
  45415. BABYLON.serializeAsColor3("diffuse")
  45416. ], StandardMaterial.prototype, "diffuseColor", void 0);
  45417. __decorate([
  45418. BABYLON.serializeAsColor3("specular")
  45419. ], StandardMaterial.prototype, "specularColor", void 0);
  45420. __decorate([
  45421. BABYLON.serializeAsColor3("emissive")
  45422. ], StandardMaterial.prototype, "emissiveColor", void 0);
  45423. __decorate([
  45424. BABYLON.serialize()
  45425. ], StandardMaterial.prototype, "specularPower", void 0);
  45426. __decorate([
  45427. BABYLON.serialize("useAlphaFromDiffuseTexture")
  45428. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  45429. __decorate([
  45430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45431. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  45432. __decorate([
  45433. BABYLON.serialize("useEmissiveAsIllumination")
  45434. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  45435. __decorate([
  45436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45437. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  45438. __decorate([
  45439. BABYLON.serialize("linkEmissiveWithDiffuse")
  45440. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  45441. __decorate([
  45442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45443. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  45444. __decorate([
  45445. BABYLON.serialize("useSpecularOverAlpha")
  45446. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  45447. __decorate([
  45448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45449. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  45450. __decorate([
  45451. BABYLON.serialize("useReflectionOverAlpha")
  45452. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  45453. __decorate([
  45454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45455. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  45456. __decorate([
  45457. BABYLON.serialize("disableLighting")
  45458. ], StandardMaterial.prototype, "_disableLighting", void 0);
  45459. __decorate([
  45460. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45461. ], StandardMaterial.prototype, "disableLighting", void 0);
  45462. __decorate([
  45463. BABYLON.serialize("useParallax")
  45464. ], StandardMaterial.prototype, "_useParallax", void 0);
  45465. __decorate([
  45466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45467. ], StandardMaterial.prototype, "useParallax", void 0);
  45468. __decorate([
  45469. BABYLON.serialize("useParallaxOcclusion")
  45470. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  45471. __decorate([
  45472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45473. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  45474. __decorate([
  45475. BABYLON.serialize()
  45476. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  45477. __decorate([
  45478. BABYLON.serialize("roughness")
  45479. ], StandardMaterial.prototype, "_roughness", void 0);
  45480. __decorate([
  45481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45482. ], StandardMaterial.prototype, "roughness", void 0);
  45483. __decorate([
  45484. BABYLON.serialize()
  45485. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  45486. __decorate([
  45487. BABYLON.serialize()
  45488. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  45489. __decorate([
  45490. BABYLON.serialize("useLightmapAsShadowmap")
  45491. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  45492. __decorate([
  45493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45494. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45495. __decorate([
  45496. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  45497. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  45498. __decorate([
  45499. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45500. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  45501. __decorate([
  45502. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  45503. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  45504. __decorate([
  45505. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45506. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  45507. __decorate([
  45508. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  45509. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  45510. __decorate([
  45511. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45512. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  45513. __decorate([
  45514. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  45515. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  45516. __decorate([
  45517. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45518. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  45519. __decorate([
  45520. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  45521. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  45522. __decorate([
  45523. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45524. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  45525. __decorate([
  45526. BABYLON.serialize("useReflectionFresnelFromSpecular")
  45527. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  45528. __decorate([
  45529. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45530. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  45531. __decorate([
  45532. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  45533. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  45534. __decorate([
  45535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45536. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  45537. __decorate([
  45538. BABYLON.serialize("maxSimultaneousLights")
  45539. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  45540. __decorate([
  45541. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45542. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  45543. __decorate([
  45544. BABYLON.serialize("invertNormalMapX")
  45545. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  45546. __decorate([
  45547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45548. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  45549. __decorate([
  45550. BABYLON.serialize("invertNormalMapY")
  45551. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  45552. __decorate([
  45553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45554. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  45555. __decorate([
  45556. BABYLON.serialize("twoSidedLighting")
  45557. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  45558. __decorate([
  45559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45560. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  45561. __decorate([
  45562. BABYLON.serialize()
  45563. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  45564. return StandardMaterial;
  45565. }(BABYLON.PushMaterial));
  45566. BABYLON.StandardMaterial = StandardMaterial;
  45567. })(BABYLON || (BABYLON = {}));
  45568. //# sourceMappingURL=babylon.standardMaterial.js.map
  45569. var BABYLON;
  45570. (function (BABYLON) {
  45571. /**
  45572. * This class implement a typical dictionary using a string as key and the generic type T as value.
  45573. * The underlying implementation relies on an associative array to ensure the best performances.
  45574. * The value can be anything including 'null' but except 'undefined'
  45575. */
  45576. var StringDictionary = (function () {
  45577. function StringDictionary() {
  45578. this._count = 0;
  45579. this._data = {};
  45580. }
  45581. /**
  45582. * This will clear this dictionary and copy the content from the 'source' one.
  45583. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  45584. * @param source the dictionary to take the content from and copy to this dictionary
  45585. */
  45586. StringDictionary.prototype.copyFrom = function (source) {
  45587. var _this = this;
  45588. this.clear();
  45589. source.forEach(function (t, v) { return _this.add(t, v); });
  45590. };
  45591. /**
  45592. * Get a value based from its key
  45593. * @param key the given key to get the matching value from
  45594. * @return the value if found, otherwise undefined is returned
  45595. */
  45596. StringDictionary.prototype.get = function (key) {
  45597. var val = this._data[key];
  45598. if (val !== undefined) {
  45599. return val;
  45600. }
  45601. return undefined;
  45602. };
  45603. /**
  45604. * Get a value from its key or add it if it doesn't exist.
  45605. * This method will ensure you that a given key/data will be present in the dictionary.
  45606. * @param key the given key to get the matching value from
  45607. * @param factory the factory that will create the value if the key is not present in the dictionary.
  45608. * The factory will only be invoked if there's no data for the given key.
  45609. * @return the value corresponding to the key.
  45610. */
  45611. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  45612. var val = this.get(key);
  45613. if (val !== undefined) {
  45614. return val;
  45615. }
  45616. val = factory(key);
  45617. if (val) {
  45618. this.add(key, val);
  45619. }
  45620. return val;
  45621. };
  45622. /**
  45623. * Get a value from its key if present in the dictionary otherwise add it
  45624. * @param key the key to get the value from
  45625. * @param val if there's no such key/value pair in the dictionary add it with this value
  45626. * @return the value corresponding to the key
  45627. */
  45628. StringDictionary.prototype.getOrAdd = function (key, val) {
  45629. var curVal = this.get(key);
  45630. if (curVal !== undefined) {
  45631. return curVal;
  45632. }
  45633. this.add(key, val);
  45634. return val;
  45635. };
  45636. /**
  45637. * Check if there's a given key in the dictionary
  45638. * @param key the key to check for
  45639. * @return true if the key is present, false otherwise
  45640. */
  45641. StringDictionary.prototype.contains = function (key) {
  45642. return this._data[key] !== undefined;
  45643. };
  45644. /**
  45645. * Add a new key and its corresponding value
  45646. * @param key the key to add
  45647. * @param value the value corresponding to the key
  45648. * @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
  45649. */
  45650. StringDictionary.prototype.add = function (key, value) {
  45651. if (this._data[key] !== undefined) {
  45652. return false;
  45653. }
  45654. this._data[key] = value;
  45655. ++this._count;
  45656. return true;
  45657. };
  45658. StringDictionary.prototype.set = function (key, value) {
  45659. if (this._data[key] === undefined) {
  45660. return false;
  45661. }
  45662. this._data[key] = value;
  45663. return true;
  45664. };
  45665. /**
  45666. * Get the element of the given key and remove it from the dictionary
  45667. * @param key
  45668. */
  45669. StringDictionary.prototype.getAndRemove = function (key) {
  45670. var val = this.get(key);
  45671. if (val !== undefined) {
  45672. delete this._data[key];
  45673. --this._count;
  45674. return val;
  45675. }
  45676. return null;
  45677. };
  45678. /**
  45679. * Remove a key/value from the dictionary.
  45680. * @param key the key to remove
  45681. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  45682. */
  45683. StringDictionary.prototype.remove = function (key) {
  45684. if (this.contains(key)) {
  45685. delete this._data[key];
  45686. --this._count;
  45687. return true;
  45688. }
  45689. return false;
  45690. };
  45691. /**
  45692. * Clear the whole content of the dictionary
  45693. */
  45694. StringDictionary.prototype.clear = function () {
  45695. this._data = {};
  45696. this._count = 0;
  45697. };
  45698. Object.defineProperty(StringDictionary.prototype, "count", {
  45699. get: function () {
  45700. return this._count;
  45701. },
  45702. enumerable: true,
  45703. configurable: true
  45704. });
  45705. /**
  45706. * Execute a callback on each key/val of the dictionary.
  45707. * Note that you can remove any element in this dictionary in the callback implementation
  45708. * @param callback the callback to execute on a given key/value pair
  45709. */
  45710. StringDictionary.prototype.forEach = function (callback) {
  45711. for (var cur in this._data) {
  45712. var val = this._data[cur];
  45713. callback(cur, val);
  45714. }
  45715. };
  45716. /**
  45717. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  45718. * If the callback returns null or undefined the method will iterate to the next key/value pair
  45719. * Note that you can remove any element in this dictionary in the callback implementation
  45720. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  45721. */
  45722. StringDictionary.prototype.first = function (callback) {
  45723. for (var cur in this._data) {
  45724. var val = this._data[cur];
  45725. var res = callback(cur, val);
  45726. if (res) {
  45727. return res;
  45728. }
  45729. }
  45730. return null;
  45731. };
  45732. return StringDictionary;
  45733. }());
  45734. BABYLON.StringDictionary = StringDictionary;
  45735. })(BABYLON || (BABYLON = {}));
  45736. //# sourceMappingURL=babylon.stringDictionary.js.map
  45737. var BABYLON;
  45738. (function (BABYLON) {
  45739. var DynamicFloatArrayElementInfo = (function () {
  45740. function DynamicFloatArrayElementInfo() {
  45741. }
  45742. return DynamicFloatArrayElementInfo;
  45743. }());
  45744. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  45745. /**
  45746. * 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.
  45747. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  45748. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  45749. * 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.
  45750. * 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.
  45751. * 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".
  45752. */
  45753. var DynamicFloatArray = (function () {
  45754. /**
  45755. * Construct an instance of the dynamic float array
  45756. * @param stride size of one element in float (i.e. not bytes!)
  45757. * @param initialElementCount the number of available entries at construction
  45758. */
  45759. function DynamicFloatArray(stride, initialElementCount) {
  45760. this.compareValueOffset = null;
  45761. this.sortingAscending = true;
  45762. this._stride = stride;
  45763. this.buffer = new Float32Array(stride * initialElementCount);
  45764. this._lastUsed = 0;
  45765. this._firstFree = 0;
  45766. this._allEntries = new Array(initialElementCount);
  45767. this._freeEntries = new Array(initialElementCount);
  45768. for (var i = 0; i < initialElementCount; i++) {
  45769. var element = new DynamicFloatArrayElementInfo();
  45770. element.offset = i * stride;
  45771. this._allEntries[i] = element;
  45772. this._freeEntries[initialElementCount - i - 1] = element;
  45773. }
  45774. }
  45775. /**
  45776. * Allocate an element in the array.
  45777. * @return the element info instance that contains the offset into the main buffer of the element's location.
  45778. * Beware, this offset may change when you call pack()
  45779. */
  45780. DynamicFloatArray.prototype.allocElement = function () {
  45781. if (this._freeEntries.length === 0) {
  45782. this._growBuffer();
  45783. }
  45784. var el = this._freeEntries.pop();
  45785. this._lastUsed = Math.max(el.offset, this._lastUsed);
  45786. if (el.offset === this._firstFree) {
  45787. if (this._freeEntries.length > 0) {
  45788. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  45789. }
  45790. else {
  45791. this._firstFree += this._stride;
  45792. }
  45793. }
  45794. return el;
  45795. };
  45796. /**
  45797. * Free the element corresponding to the given element info
  45798. * @param elInfo the element that describe the allocated element
  45799. */
  45800. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  45801. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  45802. this._freeEntries.push(elInfo);
  45803. };
  45804. /**
  45805. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  45806. * 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().
  45807. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  45808. */
  45809. DynamicFloatArray.prototype.pack = function () {
  45810. // no free slot? no need to pack
  45811. if (this._freeEntries.length === 0) {
  45812. return this.buffer;
  45813. }
  45814. // If the buffer is already packed the last used will always be lower than the first free
  45815. // 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.
  45816. if (this._lastUsed < this._firstFree) {
  45817. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  45818. return elementsBuffer_1;
  45819. }
  45820. var s = this._stride;
  45821. // 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
  45822. var lastFree = new DynamicFloatArrayElementInfo();
  45823. lastFree.offset = this.totalElementCount * s;
  45824. this._freeEntries.push(lastFree);
  45825. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  45826. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  45827. var firstFreeSlotOffset = sortedFree[0].offset;
  45828. var freeZoneSize = 1;
  45829. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  45830. var prevOffset = sortedFree[0].offset;
  45831. for (var i = 1; i < sortedFree.length; i++) {
  45832. // 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
  45833. if (firstFreeSlotOffset >= occupiedZoneSize) {
  45834. break;
  45835. }
  45836. var curFree = sortedFree[i];
  45837. var curOffset = curFree.offset;
  45838. // Compute the distance between this offset and the previous
  45839. var distance = curOffset - prevOffset;
  45840. // If the distance is the stride size, they are adjacent, it good, move to the next
  45841. if (distance === s) {
  45842. // Free zone is one element bigger
  45843. ++freeZoneSize;
  45844. // as we're about to iterate to the next, the cur becomes the previous...
  45845. prevOffset = curOffset;
  45846. continue;
  45847. }
  45848. // Distance is bigger, which means there's x element between the previous free and this one
  45849. var usedRange = (distance / s) - 1;
  45850. // Two cases the free zone is smaller than the data to move or bigger
  45851. // Copy what can fit in the free zone
  45852. var curMoveOffset = curOffset - s;
  45853. var copyCount = Math.min(freeZoneSize, usedRange);
  45854. for (var j = 0; j < copyCount; j++) {
  45855. var freeI = firstFreeSlotOffset / s;
  45856. var curI = curMoveOffset / s;
  45857. var moveEl = sortedAll[curI];
  45858. this._moveElement(moveEl, firstFreeSlotOffset);
  45859. var replacedEl = sortedAll[freeI];
  45860. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  45861. replacedEl.offset = curMoveOffset;
  45862. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  45863. sortedAll[freeI] = moveEl;
  45864. sortedAll[curI] = replacedEl;
  45865. curMoveOffset -= s;
  45866. firstFreeSlotOffset += s;
  45867. }
  45868. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  45869. if (freeZoneSize <= usedRange) {
  45870. firstFreeSlotOffset = curMoveOffset + s;
  45871. freeZoneSize = 1 + copyCount;
  45872. }
  45873. else {
  45874. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  45875. }
  45876. // as we're about to iterate to the next, the cur becomes the previous...
  45877. prevOffset = curOffset;
  45878. }
  45879. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  45880. this._lastUsed = firstFreeSlotOffset - s;
  45881. this._firstFree = firstFreeSlotOffset;
  45882. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  45883. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  45884. this._allEntries = sortedAll;
  45885. return elementsBuffer;
  45886. };
  45887. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  45888. for (var i = 0; i < this._stride; i++) {
  45889. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  45890. }
  45891. element.offset = destOffset;
  45892. };
  45893. DynamicFloatArray.prototype._growBuffer = function () {
  45894. // Allocate the new buffer with 50% more entries, copy the content of the current one
  45895. var newElCount = Math.floor(this.totalElementCount * 1.5);
  45896. var newBuffer = new Float32Array(newElCount * this._stride);
  45897. newBuffer.set(this.buffer);
  45898. var curCount = this.totalElementCount;
  45899. var addedCount = newElCount - this.totalElementCount;
  45900. for (var i = 0; i < addedCount; i++) {
  45901. var element = new DynamicFloatArrayElementInfo();
  45902. element.offset = (curCount + i) * this.stride;
  45903. this._allEntries.push(element);
  45904. this._freeEntries[addedCount - i - 1] = element;
  45905. }
  45906. this._firstFree = curCount * this.stride;
  45907. this.buffer = newBuffer;
  45908. };
  45909. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  45910. /**
  45911. * Get the total count of entries that can fit in the current buffer
  45912. * @returns the elements count
  45913. */
  45914. get: function () {
  45915. return this._allEntries.length;
  45916. },
  45917. enumerable: true,
  45918. configurable: true
  45919. });
  45920. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  45921. /**
  45922. * Get the count of free entries that can still be allocated without resizing the buffer
  45923. * @returns the free elements count
  45924. */
  45925. get: function () {
  45926. return this._freeEntries.length;
  45927. },
  45928. enumerable: true,
  45929. configurable: true
  45930. });
  45931. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  45932. /**
  45933. * Get the count of allocated elements
  45934. * @returns the allocated elements count
  45935. */
  45936. get: function () {
  45937. return this._allEntries.length - this._freeEntries.length;
  45938. },
  45939. enumerable: true,
  45940. configurable: true
  45941. });
  45942. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  45943. /**
  45944. * Return the size of one element in float
  45945. * @returns the size in float
  45946. */
  45947. get: function () {
  45948. return this._stride;
  45949. },
  45950. enumerable: true,
  45951. configurable: true
  45952. });
  45953. DynamicFloatArray.prototype.sort = function () {
  45954. var _this = this;
  45955. if (!this.compareValueOffset) {
  45956. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  45957. }
  45958. var count = this.usedElementCount;
  45959. // Do we have to (re)create the sort table?
  45960. if (!this._sortTable || this._sortTable.length < count) {
  45961. // 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...
  45962. var newCount = Math.min(this.totalElementCount, count * 2);
  45963. this._sortTable = new Array(newCount);
  45964. }
  45965. if (!this._sortedTable || this._sortedTable.length !== count) {
  45966. this._sortedTable = new Array(count);
  45967. }
  45968. // Because, you know...
  45969. this.pack();
  45970. //let stride = this.stride;
  45971. //for (let i = 0; i < count; i++) {
  45972. // let si = this._sortTable[i];
  45973. // if (!si) {
  45974. // si = new SortInfo();
  45975. // this._sortTable[i] = si;
  45976. // }
  45977. // si.entry = this._allEntries[i];
  45978. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  45979. // si.swapedOffset = null;
  45980. // this._sortedTable[i] = si;
  45981. //}
  45982. var curOffset = 0;
  45983. var stride = this.stride;
  45984. for (var i = 0; i < count; i++, curOffset += stride) {
  45985. var si = this._sortTable[i];
  45986. if (!si) {
  45987. si = new SortInfo();
  45988. this._sortTable[i] = si;
  45989. }
  45990. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  45991. si.offset = curOffset;
  45992. si.swapedOffset = null;
  45993. this._sortedTable[i] = si;
  45994. }
  45995. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  45996. if (this.sortingAscending) {
  45997. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  45998. }
  45999. else {
  46000. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  46001. }
  46002. var swapElements = function (src, dst) {
  46003. for (var i = 0; i < stride; i++) {
  46004. var tps = _this.buffer[dst + i];
  46005. _this.buffer[dst + i] = _this.buffer[src + i];
  46006. _this.buffer[src + i] = tps;
  46007. }
  46008. };
  46009. // 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:
  46010. // 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),
  46011. // and I still want something with a good algorithm complexity.
  46012. // 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,
  46013. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  46014. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  46015. // 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
  46016. // until we find a SortInfo object without a swapedOffset which means we got the right location
  46017. // 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
  46018. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  46019. for (var i = 0; i < count; i++) {
  46020. // Get the element to move
  46021. var sourceSI = this._sortedTable[i];
  46022. var destSI = this._sortTable[i];
  46023. var sourceOff = sourceSI.offset;
  46024. // If the source changed location, find the new one
  46025. if (sourceSI.swapedOffset) {
  46026. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  46027. var curSI = sourceSI;
  46028. while (curSI.swapedOffset) {
  46029. curSI = this._sortTable[curSI.swapedOffset / stride];
  46030. }
  46031. // Finally get the right location
  46032. sourceOff = curSI.offset;
  46033. }
  46034. // Tag the element being replaced with its new location
  46035. destSI.swapedOffset = sourceOff;
  46036. // Swap elements (only if needed)
  46037. if (sourceOff !== destSI.offset) {
  46038. swapElements(sourceOff, destSI.offset);
  46039. }
  46040. // Update the offset in the corresponding DFAE
  46041. //sourceSI.entry.offset = destSI.entry.offset;
  46042. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  46043. }
  46044. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  46045. return true;
  46046. };
  46047. return DynamicFloatArray;
  46048. }());
  46049. BABYLON.DynamicFloatArray = DynamicFloatArray;
  46050. var SortInfo = (function () {
  46051. function SortInfo() {
  46052. this.compareData = this.offset = this.swapedOffset = null;
  46053. }
  46054. return SortInfo;
  46055. }());
  46056. })(BABYLON || (BABYLON = {}));
  46057. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  46058. var BABYLON;
  46059. (function (BABYLON) {
  46060. var Condition = (function () {
  46061. function Condition(actionManager) {
  46062. this._actionManager = actionManager;
  46063. }
  46064. Condition.prototype.isValid = function () {
  46065. return true;
  46066. };
  46067. Condition.prototype._getProperty = function (propertyPath) {
  46068. return this._actionManager._getProperty(propertyPath);
  46069. };
  46070. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  46071. return this._actionManager._getEffectiveTarget(target, propertyPath);
  46072. };
  46073. Condition.prototype.serialize = function () {
  46074. };
  46075. Condition.prototype._serialize = function (serializedCondition) {
  46076. return {
  46077. type: 2,
  46078. children: [],
  46079. name: serializedCondition.name,
  46080. properties: serializedCondition.properties
  46081. };
  46082. };
  46083. return Condition;
  46084. }());
  46085. BABYLON.Condition = Condition;
  46086. var ValueCondition = (function (_super) {
  46087. __extends(ValueCondition, _super);
  46088. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  46089. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  46090. var _this = _super.call(this, actionManager) || this;
  46091. _this.propertyPath = propertyPath;
  46092. _this.value = value;
  46093. _this.operator = operator;
  46094. _this._target = target;
  46095. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  46096. _this._property = _this._getProperty(_this.propertyPath);
  46097. return _this;
  46098. }
  46099. Object.defineProperty(ValueCondition, "IsEqual", {
  46100. get: function () {
  46101. return ValueCondition._IsEqual;
  46102. },
  46103. enumerable: true,
  46104. configurable: true
  46105. });
  46106. Object.defineProperty(ValueCondition, "IsDifferent", {
  46107. get: function () {
  46108. return ValueCondition._IsDifferent;
  46109. },
  46110. enumerable: true,
  46111. configurable: true
  46112. });
  46113. Object.defineProperty(ValueCondition, "IsGreater", {
  46114. get: function () {
  46115. return ValueCondition._IsGreater;
  46116. },
  46117. enumerable: true,
  46118. configurable: true
  46119. });
  46120. Object.defineProperty(ValueCondition, "IsLesser", {
  46121. get: function () {
  46122. return ValueCondition._IsLesser;
  46123. },
  46124. enumerable: true,
  46125. configurable: true
  46126. });
  46127. // Methods
  46128. ValueCondition.prototype.isValid = function () {
  46129. switch (this.operator) {
  46130. case ValueCondition.IsGreater:
  46131. return this._effectiveTarget[this._property] > this.value;
  46132. case ValueCondition.IsLesser:
  46133. return this._effectiveTarget[this._property] < this.value;
  46134. case ValueCondition.IsEqual:
  46135. case ValueCondition.IsDifferent:
  46136. var check;
  46137. if (this.value.equals) {
  46138. check = this.value.equals(this._effectiveTarget[this._property]);
  46139. }
  46140. else {
  46141. check = this.value === this._effectiveTarget[this._property];
  46142. }
  46143. return this.operator === ValueCondition.IsEqual ? check : !check;
  46144. }
  46145. return false;
  46146. };
  46147. ValueCondition.prototype.serialize = function () {
  46148. return this._serialize({
  46149. name: "ValueCondition",
  46150. properties: [
  46151. BABYLON.Action._GetTargetProperty(this._target),
  46152. { name: "propertyPath", value: this.propertyPath },
  46153. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46154. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  46155. ]
  46156. });
  46157. };
  46158. ValueCondition.GetOperatorName = function (operator) {
  46159. switch (operator) {
  46160. case ValueCondition._IsEqual: return "IsEqual";
  46161. case ValueCondition._IsDifferent: return "IsDifferent";
  46162. case ValueCondition._IsGreater: return "IsGreater";
  46163. case ValueCondition._IsLesser: return "IsLesser";
  46164. default: return "";
  46165. }
  46166. };
  46167. // Statics
  46168. ValueCondition._IsEqual = 0;
  46169. ValueCondition._IsDifferent = 1;
  46170. ValueCondition._IsGreater = 2;
  46171. ValueCondition._IsLesser = 3;
  46172. return ValueCondition;
  46173. }(Condition));
  46174. BABYLON.ValueCondition = ValueCondition;
  46175. var PredicateCondition = (function (_super) {
  46176. __extends(PredicateCondition, _super);
  46177. function PredicateCondition(actionManager, predicate) {
  46178. var _this = _super.call(this, actionManager) || this;
  46179. _this.predicate = predicate;
  46180. return _this;
  46181. }
  46182. PredicateCondition.prototype.isValid = function () {
  46183. return this.predicate();
  46184. };
  46185. return PredicateCondition;
  46186. }(Condition));
  46187. BABYLON.PredicateCondition = PredicateCondition;
  46188. var StateCondition = (function (_super) {
  46189. __extends(StateCondition, _super);
  46190. function StateCondition(actionManager, target, value) {
  46191. var _this = _super.call(this, actionManager) || this;
  46192. _this.value = value;
  46193. _this._target = target;
  46194. return _this;
  46195. }
  46196. // Methods
  46197. StateCondition.prototype.isValid = function () {
  46198. return this._target.state === this.value;
  46199. };
  46200. StateCondition.prototype.serialize = function () {
  46201. return this._serialize({
  46202. name: "StateCondition",
  46203. properties: [
  46204. BABYLON.Action._GetTargetProperty(this._target),
  46205. { name: "value", value: this.value }
  46206. ]
  46207. });
  46208. };
  46209. return StateCondition;
  46210. }(Condition));
  46211. BABYLON.StateCondition = StateCondition;
  46212. })(BABYLON || (BABYLON = {}));
  46213. //# sourceMappingURL=babylon.condition.js.map
  46214. var BABYLON;
  46215. (function (BABYLON) {
  46216. var Action = (function () {
  46217. function Action(triggerOptions, condition) {
  46218. this.triggerOptions = triggerOptions;
  46219. if (triggerOptions.parameter) {
  46220. this.trigger = triggerOptions.trigger;
  46221. this._triggerParameter = triggerOptions.parameter;
  46222. }
  46223. else {
  46224. this.trigger = triggerOptions;
  46225. }
  46226. this._nextActiveAction = this;
  46227. this._condition = condition;
  46228. }
  46229. // Methods
  46230. Action.prototype._prepare = function () {
  46231. };
  46232. Action.prototype.getTriggerParameter = function () {
  46233. return this._triggerParameter;
  46234. };
  46235. Action.prototype._executeCurrent = function (evt) {
  46236. if (this._nextActiveAction._condition) {
  46237. var condition = this._nextActiveAction._condition;
  46238. var currentRenderId = this._actionManager.getScene().getRenderId();
  46239. // We cache the current evaluation for the current frame
  46240. if (condition._evaluationId === currentRenderId) {
  46241. if (!condition._currentResult) {
  46242. return;
  46243. }
  46244. }
  46245. else {
  46246. condition._evaluationId = currentRenderId;
  46247. if (!condition.isValid()) {
  46248. condition._currentResult = false;
  46249. return;
  46250. }
  46251. condition._currentResult = true;
  46252. }
  46253. }
  46254. this._nextActiveAction.execute(evt);
  46255. this.skipToNextActiveAction();
  46256. };
  46257. Action.prototype.execute = function (evt) {
  46258. };
  46259. Action.prototype.skipToNextActiveAction = function () {
  46260. if (this._nextActiveAction._child) {
  46261. if (!this._nextActiveAction._child._actionManager) {
  46262. this._nextActiveAction._child._actionManager = this._actionManager;
  46263. }
  46264. this._nextActiveAction = this._nextActiveAction._child;
  46265. }
  46266. else {
  46267. this._nextActiveAction = this;
  46268. }
  46269. };
  46270. Action.prototype.then = function (action) {
  46271. this._child = action;
  46272. action._actionManager = this._actionManager;
  46273. action._prepare();
  46274. return action;
  46275. };
  46276. Action.prototype._getProperty = function (propertyPath) {
  46277. return this._actionManager._getProperty(propertyPath);
  46278. };
  46279. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  46280. return this._actionManager._getEffectiveTarget(target, propertyPath);
  46281. };
  46282. Action.prototype.serialize = function (parent) {
  46283. };
  46284. // Called by BABYLON.Action objects in serialize(...). Internal use
  46285. Action.prototype._serialize = function (serializedAction, parent) {
  46286. var serializationObject = {
  46287. type: 1,
  46288. children: [],
  46289. name: serializedAction.name,
  46290. properties: serializedAction.properties || []
  46291. };
  46292. // Serialize child
  46293. if (this._child) {
  46294. this._child.serialize(serializationObject);
  46295. }
  46296. // Check if "this" has a condition
  46297. if (this._condition) {
  46298. var serializedCondition = this._condition.serialize();
  46299. serializedCondition.children.push(serializationObject);
  46300. if (parent) {
  46301. parent.children.push(serializedCondition);
  46302. }
  46303. return serializedCondition;
  46304. }
  46305. if (parent) {
  46306. parent.children.push(serializationObject);
  46307. }
  46308. return serializationObject;
  46309. };
  46310. Action._SerializeValueAsString = function (value) {
  46311. if (typeof value === "number") {
  46312. return value.toString();
  46313. }
  46314. if (typeof value === "boolean") {
  46315. return value ? "true" : "false";
  46316. }
  46317. if (value instanceof BABYLON.Vector2) {
  46318. return value.x + ", " + value.y;
  46319. }
  46320. if (value instanceof BABYLON.Vector3) {
  46321. return value.x + ", " + value.y + ", " + value.z;
  46322. }
  46323. if (value instanceof BABYLON.Color3) {
  46324. return value.r + ", " + value.g + ", " + value.b;
  46325. }
  46326. if (value instanceof BABYLON.Color4) {
  46327. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  46328. }
  46329. return value; // string
  46330. };
  46331. Action._GetTargetProperty = function (target) {
  46332. return {
  46333. name: "target",
  46334. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  46335. : target instanceof BABYLON.Light ? "LightProperties"
  46336. : target instanceof BABYLON.Camera ? "CameraProperties"
  46337. : "SceneProperties",
  46338. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  46339. };
  46340. };
  46341. return Action;
  46342. }());
  46343. BABYLON.Action = Action;
  46344. })(BABYLON || (BABYLON = {}));
  46345. //# sourceMappingURL=babylon.action.js.map
  46346. var BABYLON;
  46347. (function (BABYLON) {
  46348. /**
  46349. * ActionEvent is the event beint sent when an action is triggered.
  46350. */
  46351. var ActionEvent = (function () {
  46352. /**
  46353. * @param source The mesh or sprite that triggered the action.
  46354. * @param pointerX The X mouse cursor position at the time of the event
  46355. * @param pointerY The Y mouse cursor position at the time of the event
  46356. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  46357. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  46358. */
  46359. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  46360. this.source = source;
  46361. this.pointerX = pointerX;
  46362. this.pointerY = pointerY;
  46363. this.meshUnderPointer = meshUnderPointer;
  46364. this.sourceEvent = sourceEvent;
  46365. this.additionalData = additionalData;
  46366. }
  46367. /**
  46368. * Helper function to auto-create an ActionEvent from a source mesh.
  46369. * @param source The source mesh that triggered the event
  46370. * @param evt {Event} The original (browser) event
  46371. */
  46372. ActionEvent.CreateNew = function (source, evt, additionalData) {
  46373. var scene = source.getScene();
  46374. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  46375. };
  46376. /**
  46377. * Helper function to auto-create an ActionEvent from a source mesh.
  46378. * @param source The source sprite that triggered the event
  46379. * @param scene Scene associated with the sprite
  46380. * @param evt {Event} The original (browser) event
  46381. */
  46382. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  46383. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  46384. };
  46385. /**
  46386. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  46387. * @param scene the scene where the event occurred
  46388. * @param evt {Event} The original (browser) event
  46389. */
  46390. ActionEvent.CreateNewFromScene = function (scene, evt) {
  46391. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  46392. };
  46393. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  46394. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  46395. };
  46396. return ActionEvent;
  46397. }());
  46398. BABYLON.ActionEvent = ActionEvent;
  46399. /**
  46400. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  46401. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  46402. */
  46403. var ActionManager = (function () {
  46404. function ActionManager(scene) {
  46405. // Members
  46406. this.actions = new Array();
  46407. this.hoverCursor = '';
  46408. this._scene = scene;
  46409. scene._actionManagers.push(this);
  46410. }
  46411. Object.defineProperty(ActionManager, "NothingTrigger", {
  46412. get: function () {
  46413. return ActionManager._NothingTrigger;
  46414. },
  46415. enumerable: true,
  46416. configurable: true
  46417. });
  46418. Object.defineProperty(ActionManager, "OnPickTrigger", {
  46419. get: function () {
  46420. return ActionManager._OnPickTrigger;
  46421. },
  46422. enumerable: true,
  46423. configurable: true
  46424. });
  46425. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  46426. get: function () {
  46427. return ActionManager._OnLeftPickTrigger;
  46428. },
  46429. enumerable: true,
  46430. configurable: true
  46431. });
  46432. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  46433. get: function () {
  46434. return ActionManager._OnRightPickTrigger;
  46435. },
  46436. enumerable: true,
  46437. configurable: true
  46438. });
  46439. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  46440. get: function () {
  46441. return ActionManager._OnCenterPickTrigger;
  46442. },
  46443. enumerable: true,
  46444. configurable: true
  46445. });
  46446. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  46447. get: function () {
  46448. return ActionManager._OnPickDownTrigger;
  46449. },
  46450. enumerable: true,
  46451. configurable: true
  46452. });
  46453. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  46454. get: function () {
  46455. return ActionManager._OnDoublePickTrigger;
  46456. },
  46457. enumerable: true,
  46458. configurable: true
  46459. });
  46460. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  46461. get: function () {
  46462. return ActionManager._OnPickUpTrigger;
  46463. },
  46464. enumerable: true,
  46465. configurable: true
  46466. });
  46467. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  46468. /// This trigger will only be raised if you also declared a OnPickDown
  46469. get: function () {
  46470. return ActionManager._OnPickOutTrigger;
  46471. },
  46472. enumerable: true,
  46473. configurable: true
  46474. });
  46475. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  46476. get: function () {
  46477. return ActionManager._OnLongPressTrigger;
  46478. },
  46479. enumerable: true,
  46480. configurable: true
  46481. });
  46482. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  46483. get: function () {
  46484. return ActionManager._OnPointerOverTrigger;
  46485. },
  46486. enumerable: true,
  46487. configurable: true
  46488. });
  46489. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  46490. get: function () {
  46491. return ActionManager._OnPointerOutTrigger;
  46492. },
  46493. enumerable: true,
  46494. configurable: true
  46495. });
  46496. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  46497. get: function () {
  46498. return ActionManager._OnEveryFrameTrigger;
  46499. },
  46500. enumerable: true,
  46501. configurable: true
  46502. });
  46503. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  46504. get: function () {
  46505. return ActionManager._OnIntersectionEnterTrigger;
  46506. },
  46507. enumerable: true,
  46508. configurable: true
  46509. });
  46510. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  46511. get: function () {
  46512. return ActionManager._OnIntersectionExitTrigger;
  46513. },
  46514. enumerable: true,
  46515. configurable: true
  46516. });
  46517. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  46518. get: function () {
  46519. return ActionManager._OnKeyDownTrigger;
  46520. },
  46521. enumerable: true,
  46522. configurable: true
  46523. });
  46524. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  46525. get: function () {
  46526. return ActionManager._OnKeyUpTrigger;
  46527. },
  46528. enumerable: true,
  46529. configurable: true
  46530. });
  46531. // Methods
  46532. ActionManager.prototype.dispose = function () {
  46533. var index = this._scene._actionManagers.indexOf(this);
  46534. for (var i = 0; i < this.actions.length; i++) {
  46535. var action = this.actions[i];
  46536. ActionManager.Triggers[action.trigger]--;
  46537. if (ActionManager.Triggers[action.trigger] === 0) {
  46538. delete ActionManager.Triggers[action.trigger];
  46539. }
  46540. }
  46541. if (index > -1) {
  46542. this._scene._actionManagers.splice(index, 1);
  46543. }
  46544. };
  46545. ActionManager.prototype.getScene = function () {
  46546. return this._scene;
  46547. };
  46548. /**
  46549. * Does this action manager handles actions of any of the given triggers
  46550. * @param {number[]} triggers - the triggers to be tested
  46551. * @return {boolean} whether one (or more) of the triggers is handeled
  46552. */
  46553. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  46554. for (var index = 0; index < this.actions.length; index++) {
  46555. var action = this.actions[index];
  46556. if (triggers.indexOf(action.trigger) > -1) {
  46557. return true;
  46558. }
  46559. }
  46560. return false;
  46561. };
  46562. /**
  46563. * Does this action manager handles actions of a given trigger
  46564. * @param {number} trigger - the trigger to be tested
  46565. * @return {boolean} whether the trigger is handeled
  46566. */
  46567. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  46568. for (var index = 0; index < this.actions.length; index++) {
  46569. var action = this.actions[index];
  46570. if (action.trigger === trigger) {
  46571. return true;
  46572. }
  46573. }
  46574. return false;
  46575. };
  46576. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  46577. /**
  46578. * Does this action manager has pointer triggers
  46579. * @return {boolean} whether or not it has pointer triggers
  46580. */
  46581. get: function () {
  46582. for (var index = 0; index < this.actions.length; index++) {
  46583. var action = this.actions[index];
  46584. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  46585. return true;
  46586. }
  46587. }
  46588. return false;
  46589. },
  46590. enumerable: true,
  46591. configurable: true
  46592. });
  46593. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  46594. /**
  46595. * Does this action manager has pick triggers
  46596. * @return {boolean} whether or not it has pick triggers
  46597. */
  46598. get: function () {
  46599. for (var index = 0; index < this.actions.length; index++) {
  46600. var action = this.actions[index];
  46601. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  46602. return true;
  46603. }
  46604. }
  46605. return false;
  46606. },
  46607. enumerable: true,
  46608. configurable: true
  46609. });
  46610. Object.defineProperty(ActionManager, "HasTriggers", {
  46611. /**
  46612. * Does exist one action manager with at least one trigger
  46613. * @return {boolean} whether or not it exists one action manager with one trigger
  46614. **/
  46615. get: function () {
  46616. for (var t in ActionManager.Triggers) {
  46617. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46618. return true;
  46619. }
  46620. }
  46621. return false;
  46622. },
  46623. enumerable: true,
  46624. configurable: true
  46625. });
  46626. Object.defineProperty(ActionManager, "HasPickTriggers", {
  46627. /**
  46628. * Does exist one action manager with at least one pick trigger
  46629. * @return {boolean} whether or not it exists one action manager with one pick trigger
  46630. **/
  46631. get: function () {
  46632. for (var t in ActionManager.Triggers) {
  46633. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46634. var t_int = parseInt(t);
  46635. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  46636. return true;
  46637. }
  46638. }
  46639. }
  46640. return false;
  46641. },
  46642. enumerable: true,
  46643. configurable: true
  46644. });
  46645. /**
  46646. * Does exist one action manager that handles actions of a given trigger
  46647. * @param {number} trigger - the trigger to be tested
  46648. * @return {boolean} whether the trigger is handeled by at least one action manager
  46649. **/
  46650. ActionManager.HasSpecificTrigger = function (trigger) {
  46651. for (var t in ActionManager.Triggers) {
  46652. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46653. var t_int = parseInt(t);
  46654. if (t_int === trigger) {
  46655. return true;
  46656. }
  46657. }
  46658. }
  46659. return false;
  46660. };
  46661. /**
  46662. * Registers an action to this action manager
  46663. * @param {BABYLON.Action} action - the action to be registered
  46664. * @return {BABYLON.Action} the action amended (prepared) after registration
  46665. */
  46666. ActionManager.prototype.registerAction = function (action) {
  46667. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  46668. if (this.getScene().actionManager !== this) {
  46669. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  46670. return null;
  46671. }
  46672. }
  46673. this.actions.push(action);
  46674. if (ActionManager.Triggers[action.trigger]) {
  46675. ActionManager.Triggers[action.trigger]++;
  46676. }
  46677. else {
  46678. ActionManager.Triggers[action.trigger] = 1;
  46679. }
  46680. action._actionManager = this;
  46681. action._prepare();
  46682. return action;
  46683. };
  46684. /**
  46685. * Process a specific trigger
  46686. * @param {number} trigger - the trigger to process
  46687. * @param evt {BABYLON.ActionEvent} the event details to be processed
  46688. */
  46689. ActionManager.prototype.processTrigger = function (trigger, evt) {
  46690. for (var index = 0; index < this.actions.length; index++) {
  46691. var action = this.actions[index];
  46692. if (action.trigger === trigger) {
  46693. if (trigger === ActionManager.OnKeyUpTrigger
  46694. || trigger === ActionManager.OnKeyDownTrigger) {
  46695. var parameter = action.getTriggerParameter();
  46696. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  46697. if (!parameter.toLowerCase) {
  46698. continue;
  46699. }
  46700. var lowerCase = parameter.toLowerCase();
  46701. if (lowerCase !== evt.sourceEvent.key) {
  46702. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  46703. var actualkey = String.fromCharCode(unicode).toLowerCase();
  46704. if (actualkey !== lowerCase) {
  46705. continue;
  46706. }
  46707. }
  46708. }
  46709. }
  46710. action._executeCurrent(evt);
  46711. }
  46712. }
  46713. };
  46714. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  46715. var properties = propertyPath.split(".");
  46716. for (var index = 0; index < properties.length - 1; index++) {
  46717. target = target[properties[index]];
  46718. }
  46719. return target;
  46720. };
  46721. ActionManager.prototype._getProperty = function (propertyPath) {
  46722. var properties = propertyPath.split(".");
  46723. return properties[properties.length - 1];
  46724. };
  46725. ActionManager.prototype.serialize = function (name) {
  46726. var root = {
  46727. children: [],
  46728. name: name,
  46729. type: 3,
  46730. properties: [] // Empty for root but required
  46731. };
  46732. for (var i = 0; i < this.actions.length; i++) {
  46733. var triggerObject = {
  46734. type: 0,
  46735. children: [],
  46736. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  46737. properties: []
  46738. };
  46739. var triggerOptions = this.actions[i].triggerOptions;
  46740. if (triggerOptions && typeof triggerOptions !== "number") {
  46741. if (triggerOptions.parameter instanceof BABYLON.Node) {
  46742. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  46743. }
  46744. else {
  46745. var parameter = {};
  46746. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  46747. if (triggerOptions.parameter.mesh) {
  46748. parameter._meshId = triggerOptions.parameter.mesh.id;
  46749. }
  46750. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  46751. }
  46752. }
  46753. // Serialize child action, recursively
  46754. this.actions[i].serialize(triggerObject);
  46755. // Add serialized trigger
  46756. root.children.push(triggerObject);
  46757. }
  46758. return root;
  46759. };
  46760. ActionManager.Parse = function (parsedActions, object, scene) {
  46761. var actionManager = new BABYLON.ActionManager(scene);
  46762. if (object === null)
  46763. scene.actionManager = actionManager;
  46764. else
  46765. object.actionManager = actionManager;
  46766. // instanciate a new object
  46767. var instanciate = function (name, params) {
  46768. var newInstance = Object.create(BABYLON[name].prototype);
  46769. newInstance.constructor.apply(newInstance, params);
  46770. return newInstance;
  46771. };
  46772. var parseParameter = function (name, value, target, propertyPath) {
  46773. if (propertyPath === null) {
  46774. // String, boolean or float
  46775. var floatValue = parseFloat(value);
  46776. if (value === "true" || value === "false")
  46777. return value === "true";
  46778. else
  46779. return isNaN(floatValue) ? value : floatValue;
  46780. }
  46781. var effectiveTarget = propertyPath.split(".");
  46782. var values = value.split(",");
  46783. // Get effective Target
  46784. for (var i = 0; i < effectiveTarget.length; i++) {
  46785. target = target[effectiveTarget[i]];
  46786. }
  46787. // Return appropriate value with its type
  46788. if (typeof (target) === "boolean")
  46789. return values[0] === "true";
  46790. if (typeof (target) === "string")
  46791. return values[0];
  46792. // Parameters with multiple values such as Vector3 etc.
  46793. var split = new Array();
  46794. for (var i = 0; i < values.length; i++)
  46795. split.push(parseFloat(values[i]));
  46796. if (target instanceof BABYLON.Vector3)
  46797. return BABYLON.Vector3.FromArray(split);
  46798. if (target instanceof BABYLON.Vector4)
  46799. return BABYLON.Vector4.FromArray(split);
  46800. if (target instanceof BABYLON.Color3)
  46801. return BABYLON.Color3.FromArray(split);
  46802. if (target instanceof BABYLON.Color4)
  46803. return BABYLON.Color4.FromArray(split);
  46804. return parseFloat(values[0]);
  46805. };
  46806. // traverse graph per trigger
  46807. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  46808. if (combineArray === void 0) { combineArray = null; }
  46809. if (parsedAction.detached)
  46810. return;
  46811. var parameters = new Array();
  46812. var target = null;
  46813. var propertyPath = null;
  46814. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  46815. // Parameters
  46816. if (parsedAction.type === 2)
  46817. parameters.push(actionManager);
  46818. else
  46819. parameters.push(trigger);
  46820. if (combine) {
  46821. var actions = new Array();
  46822. for (var j = 0; j < parsedAction.combine.length; j++) {
  46823. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  46824. }
  46825. parameters.push(actions);
  46826. }
  46827. else {
  46828. for (var i = 0; i < parsedAction.properties.length; i++) {
  46829. var value = parsedAction.properties[i].value;
  46830. var name = parsedAction.properties[i].name;
  46831. var targetType = parsedAction.properties[i].targetType;
  46832. if (name === "target")
  46833. if (targetType !== null && targetType === "SceneProperties")
  46834. value = target = scene;
  46835. else
  46836. value = target = scene.getNodeByName(value);
  46837. else if (name === "parent")
  46838. value = scene.getNodeByName(value);
  46839. else if (name === "sound")
  46840. value = scene.getSoundByName(value);
  46841. else if (name !== "propertyPath") {
  46842. if (parsedAction.type === 2 && name === "operator")
  46843. value = BABYLON.ValueCondition[value];
  46844. else
  46845. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  46846. }
  46847. else {
  46848. propertyPath = value;
  46849. }
  46850. parameters.push(value);
  46851. }
  46852. }
  46853. if (combineArray === null) {
  46854. parameters.push(condition);
  46855. }
  46856. else {
  46857. parameters.push(null);
  46858. }
  46859. // If interpolate value action
  46860. if (parsedAction.name === "InterpolateValueAction") {
  46861. var param = parameters[parameters.length - 2];
  46862. parameters[parameters.length - 1] = param;
  46863. parameters[parameters.length - 2] = condition;
  46864. }
  46865. // Action or condition(s) and not CombineAction
  46866. var newAction = instanciate(parsedAction.name, parameters);
  46867. if (newAction instanceof BABYLON.Condition && condition !== null) {
  46868. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  46869. if (action)
  46870. action.then(nothing);
  46871. else
  46872. actionManager.registerAction(nothing);
  46873. action = nothing;
  46874. }
  46875. if (combineArray === null) {
  46876. if (newAction instanceof BABYLON.Condition) {
  46877. condition = newAction;
  46878. newAction = action;
  46879. }
  46880. else {
  46881. condition = null;
  46882. if (action)
  46883. action.then(newAction);
  46884. else
  46885. actionManager.registerAction(newAction);
  46886. }
  46887. }
  46888. else {
  46889. combineArray.push(newAction);
  46890. }
  46891. for (var i = 0; i < parsedAction.children.length; i++)
  46892. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  46893. };
  46894. // triggers
  46895. for (var i = 0; i < parsedActions.children.length; i++) {
  46896. var triggerParams;
  46897. var trigger = parsedActions.children[i];
  46898. if (trigger.properties.length > 0) {
  46899. var param = trigger.properties[0].value;
  46900. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  46901. if (value._meshId) {
  46902. value.mesh = scene.getMeshByID(value._meshId);
  46903. }
  46904. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  46905. }
  46906. else
  46907. triggerParams = BABYLON.ActionManager[trigger.name];
  46908. for (var j = 0; j < trigger.children.length; j++) {
  46909. if (!trigger.detached)
  46910. traverse(trigger.children[j], triggerParams, null, null);
  46911. }
  46912. }
  46913. };
  46914. ActionManager.GetTriggerName = function (trigger) {
  46915. switch (trigger) {
  46916. case 0: return "NothingTrigger";
  46917. case 1: return "OnPickTrigger";
  46918. case 2: return "OnLeftPickTrigger";
  46919. case 3: return "OnRightPickTrigger";
  46920. case 4: return "OnCenterPickTrigger";
  46921. case 5: return "OnPickDownTrigger";
  46922. case 6: return "OnPickUpTrigger";
  46923. case 7: return "OnLongPressTrigger";
  46924. case 8: return "OnPointerOverTrigger";
  46925. case 9: return "OnPointerOutTrigger";
  46926. case 10: return "OnEveryFrameTrigger";
  46927. case 11: return "OnIntersectionEnterTrigger";
  46928. case 12: return "OnIntersectionExitTrigger";
  46929. case 13: return "OnKeyDownTrigger";
  46930. case 14: return "OnKeyUpTrigger";
  46931. case 15: return "OnPickOutTrigger";
  46932. default: return "";
  46933. }
  46934. };
  46935. // Statics
  46936. ActionManager._NothingTrigger = 0;
  46937. ActionManager._OnPickTrigger = 1;
  46938. ActionManager._OnLeftPickTrigger = 2;
  46939. ActionManager._OnRightPickTrigger = 3;
  46940. ActionManager._OnCenterPickTrigger = 4;
  46941. ActionManager._OnPickDownTrigger = 5;
  46942. ActionManager._OnDoublePickTrigger = 6;
  46943. ActionManager._OnPickUpTrigger = 7;
  46944. ActionManager._OnLongPressTrigger = 8;
  46945. ActionManager._OnPointerOverTrigger = 9;
  46946. ActionManager._OnPointerOutTrigger = 10;
  46947. ActionManager._OnEveryFrameTrigger = 11;
  46948. ActionManager._OnIntersectionEnterTrigger = 12;
  46949. ActionManager._OnIntersectionExitTrigger = 13;
  46950. ActionManager._OnKeyDownTrigger = 14;
  46951. ActionManager._OnKeyUpTrigger = 15;
  46952. ActionManager._OnPickOutTrigger = 16;
  46953. ActionManager.Triggers = {};
  46954. return ActionManager;
  46955. }());
  46956. BABYLON.ActionManager = ActionManager;
  46957. })(BABYLON || (BABYLON = {}));
  46958. //# sourceMappingURL=babylon.actionManager.js.map
  46959. var BABYLON;
  46960. (function (BABYLON) {
  46961. var InterpolateValueAction = (function (_super) {
  46962. __extends(InterpolateValueAction, _super);
  46963. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  46964. if (duration === void 0) { duration = 1000; }
  46965. var _this = _super.call(this, triggerOptions, condition) || this;
  46966. _this.propertyPath = propertyPath;
  46967. _this.value = value;
  46968. _this.duration = duration;
  46969. _this.stopOtherAnimations = stopOtherAnimations;
  46970. _this.onInterpolationDone = onInterpolationDone;
  46971. _this._target = _this._effectiveTarget = target;
  46972. return _this;
  46973. }
  46974. InterpolateValueAction.prototype._prepare = function () {
  46975. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46976. this._property = this._getProperty(this.propertyPath);
  46977. };
  46978. InterpolateValueAction.prototype.execute = function () {
  46979. var scene = this._actionManager.getScene();
  46980. var keys = [
  46981. {
  46982. frame: 0,
  46983. value: this._effectiveTarget[this._property]
  46984. }, {
  46985. frame: 100,
  46986. value: this.value
  46987. }
  46988. ];
  46989. var dataType;
  46990. if (typeof this.value === "number") {
  46991. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  46992. }
  46993. else if (this.value instanceof BABYLON.Color3) {
  46994. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  46995. }
  46996. else if (this.value instanceof BABYLON.Vector3) {
  46997. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  46998. }
  46999. else if (this.value instanceof BABYLON.Matrix) {
  47000. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  47001. }
  47002. else if (this.value instanceof BABYLON.Quaternion) {
  47003. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  47004. }
  47005. else {
  47006. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  47007. return;
  47008. }
  47009. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  47010. animation.setKeys(keys);
  47011. if (this.stopOtherAnimations) {
  47012. scene.stopAnimation(this._effectiveTarget);
  47013. }
  47014. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  47015. };
  47016. InterpolateValueAction.prototype.serialize = function (parent) {
  47017. return _super.prototype._serialize.call(this, {
  47018. name: "InterpolateValueAction",
  47019. properties: [
  47020. BABYLON.Action._GetTargetProperty(this._target),
  47021. { name: "propertyPath", value: this.propertyPath },
  47022. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47023. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  47024. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  47025. ]
  47026. }, parent);
  47027. };
  47028. return InterpolateValueAction;
  47029. }(BABYLON.Action));
  47030. BABYLON.InterpolateValueAction = InterpolateValueAction;
  47031. })(BABYLON || (BABYLON = {}));
  47032. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  47033. var BABYLON;
  47034. (function (BABYLON) {
  47035. var SwitchBooleanAction = (function (_super) {
  47036. __extends(SwitchBooleanAction, _super);
  47037. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  47038. var _this = _super.call(this, triggerOptions, condition) || this;
  47039. _this.propertyPath = propertyPath;
  47040. _this._target = _this._effectiveTarget = target;
  47041. return _this;
  47042. }
  47043. SwitchBooleanAction.prototype._prepare = function () {
  47044. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47045. this._property = this._getProperty(this.propertyPath);
  47046. };
  47047. SwitchBooleanAction.prototype.execute = function () {
  47048. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  47049. };
  47050. SwitchBooleanAction.prototype.serialize = function (parent) {
  47051. return _super.prototype._serialize.call(this, {
  47052. name: "SwitchBooleanAction",
  47053. properties: [
  47054. BABYLON.Action._GetTargetProperty(this._target),
  47055. { name: "propertyPath", value: this.propertyPath }
  47056. ]
  47057. }, parent);
  47058. };
  47059. return SwitchBooleanAction;
  47060. }(BABYLON.Action));
  47061. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  47062. var SetStateAction = (function (_super) {
  47063. __extends(SetStateAction, _super);
  47064. function SetStateAction(triggerOptions, target, value, condition) {
  47065. var _this = _super.call(this, triggerOptions, condition) || this;
  47066. _this.value = value;
  47067. _this._target = target;
  47068. return _this;
  47069. }
  47070. SetStateAction.prototype.execute = function () {
  47071. this._target.state = this.value;
  47072. };
  47073. SetStateAction.prototype.serialize = function (parent) {
  47074. return _super.prototype._serialize.call(this, {
  47075. name: "SetStateAction",
  47076. properties: [
  47077. BABYLON.Action._GetTargetProperty(this._target),
  47078. { name: "value", value: this.value }
  47079. ]
  47080. }, parent);
  47081. };
  47082. return SetStateAction;
  47083. }(BABYLON.Action));
  47084. BABYLON.SetStateAction = SetStateAction;
  47085. var SetValueAction = (function (_super) {
  47086. __extends(SetValueAction, _super);
  47087. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  47088. var _this = _super.call(this, triggerOptions, condition) || this;
  47089. _this.propertyPath = propertyPath;
  47090. _this.value = value;
  47091. _this._target = _this._effectiveTarget = target;
  47092. return _this;
  47093. }
  47094. SetValueAction.prototype._prepare = function () {
  47095. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47096. this._property = this._getProperty(this.propertyPath);
  47097. };
  47098. SetValueAction.prototype.execute = function () {
  47099. this._effectiveTarget[this._property] = this.value;
  47100. if (this._target.markAsDirty) {
  47101. this._target.markAsDirty(this._property);
  47102. }
  47103. };
  47104. SetValueAction.prototype.serialize = function (parent) {
  47105. return _super.prototype._serialize.call(this, {
  47106. name: "SetValueAction",
  47107. properties: [
  47108. BABYLON.Action._GetTargetProperty(this._target),
  47109. { name: "propertyPath", value: this.propertyPath },
  47110. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  47111. ]
  47112. }, parent);
  47113. };
  47114. return SetValueAction;
  47115. }(BABYLON.Action));
  47116. BABYLON.SetValueAction = SetValueAction;
  47117. var IncrementValueAction = (function (_super) {
  47118. __extends(IncrementValueAction, _super);
  47119. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  47120. var _this = _super.call(this, triggerOptions, condition) || this;
  47121. _this.propertyPath = propertyPath;
  47122. _this.value = value;
  47123. _this._target = _this._effectiveTarget = target;
  47124. return _this;
  47125. }
  47126. IncrementValueAction.prototype._prepare = function () {
  47127. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47128. this._property = this._getProperty(this.propertyPath);
  47129. if (typeof this._effectiveTarget[this._property] !== "number") {
  47130. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  47131. }
  47132. };
  47133. IncrementValueAction.prototype.execute = function () {
  47134. this._effectiveTarget[this._property] += this.value;
  47135. if (this._target.markAsDirty) {
  47136. this._target.markAsDirty(this._property);
  47137. }
  47138. };
  47139. IncrementValueAction.prototype.serialize = function (parent) {
  47140. return _super.prototype._serialize.call(this, {
  47141. name: "IncrementValueAction",
  47142. properties: [
  47143. BABYLON.Action._GetTargetProperty(this._target),
  47144. { name: "propertyPath", value: this.propertyPath },
  47145. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  47146. ]
  47147. }, parent);
  47148. };
  47149. return IncrementValueAction;
  47150. }(BABYLON.Action));
  47151. BABYLON.IncrementValueAction = IncrementValueAction;
  47152. var PlayAnimationAction = (function (_super) {
  47153. __extends(PlayAnimationAction, _super);
  47154. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  47155. var _this = _super.call(this, triggerOptions, condition) || this;
  47156. _this.from = from;
  47157. _this.to = to;
  47158. _this.loop = loop;
  47159. _this._target = target;
  47160. return _this;
  47161. }
  47162. PlayAnimationAction.prototype._prepare = function () {
  47163. };
  47164. PlayAnimationAction.prototype.execute = function () {
  47165. var scene = this._actionManager.getScene();
  47166. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  47167. };
  47168. PlayAnimationAction.prototype.serialize = function (parent) {
  47169. return _super.prototype._serialize.call(this, {
  47170. name: "PlayAnimationAction",
  47171. properties: [
  47172. BABYLON.Action._GetTargetProperty(this._target),
  47173. { name: "from", value: String(this.from) },
  47174. { name: "to", value: String(this.to) },
  47175. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  47176. ]
  47177. }, parent);
  47178. };
  47179. return PlayAnimationAction;
  47180. }(BABYLON.Action));
  47181. BABYLON.PlayAnimationAction = PlayAnimationAction;
  47182. var StopAnimationAction = (function (_super) {
  47183. __extends(StopAnimationAction, _super);
  47184. function StopAnimationAction(triggerOptions, target, condition) {
  47185. var _this = _super.call(this, triggerOptions, condition) || this;
  47186. _this._target = target;
  47187. return _this;
  47188. }
  47189. StopAnimationAction.prototype._prepare = function () {
  47190. };
  47191. StopAnimationAction.prototype.execute = function () {
  47192. var scene = this._actionManager.getScene();
  47193. scene.stopAnimation(this._target);
  47194. };
  47195. StopAnimationAction.prototype.serialize = function (parent) {
  47196. return _super.prototype._serialize.call(this, {
  47197. name: "StopAnimationAction",
  47198. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  47199. }, parent);
  47200. };
  47201. return StopAnimationAction;
  47202. }(BABYLON.Action));
  47203. BABYLON.StopAnimationAction = StopAnimationAction;
  47204. var DoNothingAction = (function (_super) {
  47205. __extends(DoNothingAction, _super);
  47206. function DoNothingAction(triggerOptions, condition) {
  47207. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  47208. return _super.call(this, triggerOptions, condition) || this;
  47209. }
  47210. DoNothingAction.prototype.execute = function () {
  47211. };
  47212. DoNothingAction.prototype.serialize = function (parent) {
  47213. return _super.prototype._serialize.call(this, {
  47214. name: "DoNothingAction",
  47215. properties: []
  47216. }, parent);
  47217. };
  47218. return DoNothingAction;
  47219. }(BABYLON.Action));
  47220. BABYLON.DoNothingAction = DoNothingAction;
  47221. var CombineAction = (function (_super) {
  47222. __extends(CombineAction, _super);
  47223. function CombineAction(triggerOptions, children, condition) {
  47224. var _this = _super.call(this, triggerOptions, condition) || this;
  47225. _this.children = children;
  47226. return _this;
  47227. }
  47228. CombineAction.prototype._prepare = function () {
  47229. for (var index = 0; index < this.children.length; index++) {
  47230. this.children[index]._actionManager = this._actionManager;
  47231. this.children[index]._prepare();
  47232. }
  47233. };
  47234. CombineAction.prototype.execute = function (evt) {
  47235. for (var index = 0; index < this.children.length; index++) {
  47236. this.children[index].execute(evt);
  47237. }
  47238. };
  47239. CombineAction.prototype.serialize = function (parent) {
  47240. var serializationObject = _super.prototype._serialize.call(this, {
  47241. name: "CombineAction",
  47242. properties: [],
  47243. combine: []
  47244. }, parent);
  47245. for (var i = 0; i < this.children.length; i++) {
  47246. serializationObject.combine.push(this.children[i].serialize(null));
  47247. }
  47248. return serializationObject;
  47249. };
  47250. return CombineAction;
  47251. }(BABYLON.Action));
  47252. BABYLON.CombineAction = CombineAction;
  47253. var ExecuteCodeAction = (function (_super) {
  47254. __extends(ExecuteCodeAction, _super);
  47255. function ExecuteCodeAction(triggerOptions, func, condition) {
  47256. var _this = _super.call(this, triggerOptions, condition) || this;
  47257. _this.func = func;
  47258. return _this;
  47259. }
  47260. ExecuteCodeAction.prototype.execute = function (evt) {
  47261. this.func(evt);
  47262. };
  47263. return ExecuteCodeAction;
  47264. }(BABYLON.Action));
  47265. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  47266. var SetParentAction = (function (_super) {
  47267. __extends(SetParentAction, _super);
  47268. function SetParentAction(triggerOptions, target, parent, condition) {
  47269. var _this = _super.call(this, triggerOptions, condition) || this;
  47270. _this._target = target;
  47271. _this._parent = parent;
  47272. return _this;
  47273. }
  47274. SetParentAction.prototype._prepare = function () {
  47275. };
  47276. SetParentAction.prototype.execute = function () {
  47277. if (this._target.parent === this._parent) {
  47278. return;
  47279. }
  47280. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  47281. invertParentWorldMatrix.invert();
  47282. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  47283. this._target.parent = this._parent;
  47284. };
  47285. SetParentAction.prototype.serialize = function (parent) {
  47286. return _super.prototype._serialize.call(this, {
  47287. name: "SetParentAction",
  47288. properties: [
  47289. BABYLON.Action._GetTargetProperty(this._target),
  47290. BABYLON.Action._GetTargetProperty(this._parent),
  47291. ]
  47292. }, parent);
  47293. };
  47294. return SetParentAction;
  47295. }(BABYLON.Action));
  47296. BABYLON.SetParentAction = SetParentAction;
  47297. var PlaySoundAction = (function (_super) {
  47298. __extends(PlaySoundAction, _super);
  47299. function PlaySoundAction(triggerOptions, sound, condition) {
  47300. var _this = _super.call(this, triggerOptions, condition) || this;
  47301. _this._sound = sound;
  47302. return _this;
  47303. }
  47304. PlaySoundAction.prototype._prepare = function () {
  47305. };
  47306. PlaySoundAction.prototype.execute = function () {
  47307. if (this._sound !== undefined)
  47308. this._sound.play();
  47309. };
  47310. PlaySoundAction.prototype.serialize = function (parent) {
  47311. return _super.prototype._serialize.call(this, {
  47312. name: "PlaySoundAction",
  47313. properties: [{ name: "sound", value: this._sound.name }]
  47314. }, parent);
  47315. };
  47316. return PlaySoundAction;
  47317. }(BABYLON.Action));
  47318. BABYLON.PlaySoundAction = PlaySoundAction;
  47319. var StopSoundAction = (function (_super) {
  47320. __extends(StopSoundAction, _super);
  47321. function StopSoundAction(triggerOptions, sound, condition) {
  47322. var _this = _super.call(this, triggerOptions, condition) || this;
  47323. _this._sound = sound;
  47324. return _this;
  47325. }
  47326. StopSoundAction.prototype._prepare = function () {
  47327. };
  47328. StopSoundAction.prototype.execute = function () {
  47329. if (this._sound !== undefined)
  47330. this._sound.stop();
  47331. };
  47332. StopSoundAction.prototype.serialize = function (parent) {
  47333. return _super.prototype._serialize.call(this, {
  47334. name: "StopSoundAction",
  47335. properties: [{ name: "sound", value: this._sound.name }]
  47336. }, parent);
  47337. };
  47338. return StopSoundAction;
  47339. }(BABYLON.Action));
  47340. BABYLON.StopSoundAction = StopSoundAction;
  47341. })(BABYLON || (BABYLON = {}));
  47342. //# sourceMappingURL=babylon.directActions.js.map
  47343. var BABYLON;
  47344. (function (BABYLON) {
  47345. var Debug;
  47346. (function (Debug) {
  47347. /**
  47348. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  47349. */
  47350. var SkeletonViewer = (function () {
  47351. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  47352. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  47353. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  47354. this.skeleton = skeleton;
  47355. this.mesh = mesh;
  47356. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  47357. this.renderingGroupId = renderingGroupId;
  47358. this.color = BABYLON.Color3.White();
  47359. this._debugLines = [];
  47360. this._isEnabled = false;
  47361. this._scene = scene;
  47362. this.update();
  47363. this._renderFunction = this.update.bind(this);
  47364. }
  47365. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  47366. get: function () {
  47367. return this._isEnabled;
  47368. },
  47369. set: function (value) {
  47370. if (this._isEnabled === value) {
  47371. return;
  47372. }
  47373. this._isEnabled = value;
  47374. if (value) {
  47375. this._scene.registerBeforeRender(this._renderFunction);
  47376. }
  47377. else {
  47378. this._scene.unregisterBeforeRender(this._renderFunction);
  47379. }
  47380. },
  47381. enumerable: true,
  47382. configurable: true
  47383. });
  47384. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  47385. if (x === void 0) { x = 0; }
  47386. if (y === void 0) { y = 0; }
  47387. if (z === void 0) { z = 0; }
  47388. var tmat = BABYLON.Tmp.Matrix[0];
  47389. var parentBone = bone.getParent();
  47390. tmat.copyFrom(bone.getLocalMatrix());
  47391. if (x !== 0 || y !== 0 || z !== 0) {
  47392. var tmat2 = BABYLON.Tmp.Matrix[1];
  47393. BABYLON.Matrix.IdentityToRef(tmat2);
  47394. tmat2.m[12] = x;
  47395. tmat2.m[13] = y;
  47396. tmat2.m[14] = z;
  47397. tmat2.multiplyToRef(tmat, tmat);
  47398. }
  47399. if (parentBone) {
  47400. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  47401. }
  47402. tmat.multiplyToRef(meshMat, tmat);
  47403. position.x = tmat.m[12];
  47404. position.y = tmat.m[13];
  47405. position.z = tmat.m[14];
  47406. };
  47407. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  47408. var len = bones.length;
  47409. var meshPos = this.mesh.position;
  47410. for (var i = 0; i < len; i++) {
  47411. var bone = bones[i];
  47412. var points = this._debugLines[i];
  47413. if (!points) {
  47414. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47415. this._debugLines[i] = points;
  47416. }
  47417. this._getBonePosition(points[0], bone, meshMat);
  47418. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  47419. points[0].subtractInPlace(meshPos);
  47420. points[1].subtractInPlace(meshPos);
  47421. }
  47422. };
  47423. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  47424. var len = bones.length;
  47425. var boneNum = 0;
  47426. var meshPos = this.mesh.position;
  47427. for (var i = len - 1; i >= 0; i--) {
  47428. var childBone = bones[i];
  47429. var parentBone = childBone.getParent();
  47430. if (!parentBone) {
  47431. continue;
  47432. }
  47433. var points = this._debugLines[boneNum];
  47434. if (!points) {
  47435. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47436. this._debugLines[boneNum] = points;
  47437. }
  47438. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  47439. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  47440. points[0].subtractInPlace(meshPos);
  47441. points[1].subtractInPlace(meshPos);
  47442. boneNum++;
  47443. }
  47444. };
  47445. SkeletonViewer.prototype.update = function () {
  47446. if (this.autoUpdateBonesMatrices) {
  47447. this.skeleton.computeAbsoluteTransforms();
  47448. }
  47449. if (this.skeleton.bones[0].length === undefined) {
  47450. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  47451. }
  47452. else {
  47453. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  47454. }
  47455. if (!this._debugMesh) {
  47456. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  47457. this._debugMesh.renderingGroupId = this.renderingGroupId;
  47458. }
  47459. else {
  47460. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  47461. }
  47462. this._debugMesh.position.copyFrom(this.mesh.position);
  47463. this._debugMesh.color = this.color;
  47464. };
  47465. SkeletonViewer.prototype.dispose = function () {
  47466. if (this._debugMesh) {
  47467. this.isEnabled = false;
  47468. this._debugMesh.dispose();
  47469. this._debugMesh = null;
  47470. }
  47471. };
  47472. return SkeletonViewer;
  47473. }());
  47474. Debug.SkeletonViewer = SkeletonViewer;
  47475. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47476. })(BABYLON || (BABYLON = {}));
  47477. //# sourceMappingURL=babylon.skeletonViewer.js.map
  47478. var BABYLON;
  47479. (function (BABYLON) {
  47480. var Debug;
  47481. (function (Debug) {
  47482. var AxesViewer = (function () {
  47483. function AxesViewer(scene, scaleLines) {
  47484. if (scaleLines === void 0) { scaleLines = 1; }
  47485. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47486. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47487. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47488. this.scaleLines = 1;
  47489. this.scaleLines = scaleLines;
  47490. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  47491. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  47492. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  47493. this._xmesh.renderingGroupId = 2;
  47494. this._ymesh.renderingGroupId = 2;
  47495. this._zmesh.renderingGroupId = 2;
  47496. this._xmesh.material.checkReadyOnlyOnce = true;
  47497. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  47498. this._ymesh.material.checkReadyOnlyOnce = true;
  47499. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  47500. this._zmesh.material.checkReadyOnlyOnce = true;
  47501. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  47502. this.scene = scene;
  47503. }
  47504. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  47505. var scaleLines = this.scaleLines;
  47506. this._xmesh.position.copyFrom(position);
  47507. this._ymesh.position.copyFrom(position);
  47508. this._zmesh.position.copyFrom(position);
  47509. var point2 = this._xline[1];
  47510. point2.x = xaxis.x * scaleLines;
  47511. point2.y = xaxis.y * scaleLines;
  47512. point2.z = xaxis.z * scaleLines;
  47513. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  47514. point2 = this._yline[1];
  47515. point2.x = yaxis.x * scaleLines;
  47516. point2.y = yaxis.y * scaleLines;
  47517. point2.z = yaxis.z * scaleLines;
  47518. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  47519. point2 = this._zline[1];
  47520. point2.x = zaxis.x * scaleLines;
  47521. point2.y = zaxis.y * scaleLines;
  47522. point2.z = zaxis.z * scaleLines;
  47523. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  47524. };
  47525. AxesViewer.prototype.dispose = function () {
  47526. if (this._xmesh) {
  47527. this._xmesh.dispose();
  47528. this._ymesh.dispose();
  47529. this._zmesh.dispose();
  47530. this._xmesh = null;
  47531. this._ymesh = null;
  47532. this._zmesh = null;
  47533. this._xline = null;
  47534. this._yline = null;
  47535. this._zline = null;
  47536. this.scene = null;
  47537. }
  47538. };
  47539. return AxesViewer;
  47540. }());
  47541. Debug.AxesViewer = AxesViewer;
  47542. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47543. })(BABYLON || (BABYLON = {}));
  47544. //# sourceMappingURL=babylon.axesViewer.js.map
  47545. var BABYLON;
  47546. (function (BABYLON) {
  47547. var Debug;
  47548. (function (Debug) {
  47549. var BoneAxesViewer = (function (_super) {
  47550. __extends(BoneAxesViewer, _super);
  47551. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  47552. if (scaleLines === void 0) { scaleLines = 1; }
  47553. var _this = _super.call(this, scene, scaleLines) || this;
  47554. _this.pos = BABYLON.Vector3.Zero();
  47555. _this.xaxis = BABYLON.Vector3.Zero();
  47556. _this.yaxis = BABYLON.Vector3.Zero();
  47557. _this.zaxis = BABYLON.Vector3.Zero();
  47558. _this.mesh = mesh;
  47559. _this.bone = bone;
  47560. return _this;
  47561. }
  47562. BoneAxesViewer.prototype.update = function () {
  47563. var bone = this.bone;
  47564. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  47565. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  47566. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  47567. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  47568. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  47569. };
  47570. BoneAxesViewer.prototype.dispose = function () {
  47571. if (this.pos) {
  47572. this.pos = null;
  47573. this.xaxis = null;
  47574. this.yaxis = null;
  47575. this.zaxis = null;
  47576. this.mesh = null;
  47577. this.bone = null;
  47578. _super.prototype.dispose.call(this);
  47579. }
  47580. };
  47581. return BoneAxesViewer;
  47582. }(Debug.AxesViewer));
  47583. Debug.BoneAxesViewer = BoneAxesViewer;
  47584. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47585. })(BABYLON || (BABYLON = {}));
  47586. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  47587. var BABYLON;
  47588. (function (BABYLON) {
  47589. var RayHelper = (function () {
  47590. function RayHelper(ray) {
  47591. this.ray = ray;
  47592. }
  47593. RayHelper.CreateAndShow = function (ray, scene, color) {
  47594. var helper = new RayHelper(ray);
  47595. helper.show(scene, color);
  47596. return helper;
  47597. };
  47598. RayHelper.prototype.show = function (scene, color) {
  47599. if (!this._renderFunction) {
  47600. var ray = this.ray;
  47601. this._renderFunction = this._render.bind(this);
  47602. this._scene = scene;
  47603. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  47604. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  47605. this._scene.registerBeforeRender(this._renderFunction);
  47606. }
  47607. if (color) {
  47608. this._renderLine.color.copyFrom(color);
  47609. }
  47610. };
  47611. RayHelper.prototype.hide = function () {
  47612. if (this._renderFunction) {
  47613. this._scene.unregisterBeforeRender(this._renderFunction);
  47614. this._scene = null;
  47615. this._renderFunction = null;
  47616. this._renderLine.dispose();
  47617. this._renderLine = null;
  47618. this._renderPoints = null;
  47619. }
  47620. };
  47621. RayHelper.prototype._render = function () {
  47622. var ray = this.ray;
  47623. var point = this._renderPoints[1];
  47624. var len = Math.min(ray.length, 1000000);
  47625. point.copyFrom(ray.direction);
  47626. point.scaleInPlace(len);
  47627. point.addInPlace(ray.origin);
  47628. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  47629. };
  47630. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  47631. this._attachedToMesh = mesh;
  47632. var ray = this.ray;
  47633. if (!ray.direction) {
  47634. ray.direction = BABYLON.Vector3.Zero();
  47635. }
  47636. if (!ray.origin) {
  47637. ray.origin = BABYLON.Vector3.Zero();
  47638. }
  47639. if (length) {
  47640. ray.length = length;
  47641. }
  47642. if (!meshSpaceOrigin) {
  47643. meshSpaceOrigin = BABYLON.Vector3.Zero();
  47644. }
  47645. if (!meshSpaceDirection) {
  47646. // -1 so that this will work with Mesh.lookAt
  47647. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  47648. }
  47649. if (!this._meshSpaceDirection) {
  47650. this._meshSpaceDirection = meshSpaceDirection.clone();
  47651. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  47652. }
  47653. else {
  47654. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  47655. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  47656. }
  47657. if (!this._updateToMeshFunction) {
  47658. this._updateToMeshFunction = this._updateToMesh.bind(this);
  47659. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  47660. }
  47661. this._updateToMesh();
  47662. };
  47663. RayHelper.prototype.detachFromMesh = function () {
  47664. if (this._attachedToMesh) {
  47665. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  47666. this._attachedToMesh = null;
  47667. this._updateToMeshFunction = null;
  47668. }
  47669. };
  47670. RayHelper.prototype._updateToMesh = function () {
  47671. var ray = this.ray;
  47672. if (this._attachedToMesh._isDisposed) {
  47673. this.detachFromMesh();
  47674. return;
  47675. }
  47676. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  47677. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  47678. };
  47679. RayHelper.prototype.dispose = function () {
  47680. this.hide();
  47681. this.detachFromMesh();
  47682. this.ray = null;
  47683. };
  47684. return RayHelper;
  47685. }());
  47686. BABYLON.RayHelper = RayHelper;
  47687. })(BABYLON || (BABYLON = {}));
  47688. //# sourceMappingURL=babylon.rayHelper.js.map
  47689. var BABYLON;
  47690. (function (BABYLON) {
  47691. var DebugLayer = (function () {
  47692. function DebugLayer(scene) {
  47693. this._scene = scene;
  47694. }
  47695. /** Creates the inspector window. */
  47696. DebugLayer.prototype._createInspector = function (config) {
  47697. if (config === void 0) { config = {}; }
  47698. var popup = config.popup || false;
  47699. var initialTab = config.initialTab || 0;
  47700. var parentElement = config.parentElement || null;
  47701. if (!this._inspector) {
  47702. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  47703. } // else nothing to do,; instance is already existing
  47704. };
  47705. DebugLayer.prototype.isVisible = function () {
  47706. if (!this._inspector) {
  47707. return false;
  47708. }
  47709. return true;
  47710. };
  47711. DebugLayer.prototype.hide = function () {
  47712. if (this._inspector) {
  47713. try {
  47714. this._inspector.dispose();
  47715. }
  47716. catch (e) {
  47717. // If the inspector has been removed directly from the inspector tool
  47718. }
  47719. this._inspector = null;
  47720. }
  47721. };
  47722. DebugLayer.prototype.show = function (config) {
  47723. if (config === void 0) { config = {}; }
  47724. if (typeof INSPECTOR == 'undefined') {
  47725. // Load inspector and add it to the DOM
  47726. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  47727. }
  47728. else {
  47729. // Otherwise creates the inspector
  47730. this._createInspector(config);
  47731. }
  47732. };
  47733. // Get protocol used - http or https
  47734. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  47735. return DebugLayer;
  47736. }());
  47737. BABYLON.DebugLayer = DebugLayer;
  47738. })(BABYLON || (BABYLON = {}));
  47739. //# sourceMappingURL=babylon.debugLayer.js.map
  47740. var BABYLON;
  47741. (function (BABYLON) {
  47742. var Debug;
  47743. (function (Debug) {
  47744. var PhysicsViewer = (function () {
  47745. function PhysicsViewer(scene) {
  47746. this._impostors = [];
  47747. this._meshes = [];
  47748. this._numMeshes = 0;
  47749. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47750. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  47751. }
  47752. PhysicsViewer.prototype._updateDebugMeshes = function () {
  47753. var plugin = this._physicsEnginePlugin;
  47754. for (var i = 0; i < this._numMeshes; i++) {
  47755. if (this._impostors[i].isDisposed) {
  47756. this.hideImpostor(this._impostors[i--]);
  47757. }
  47758. else {
  47759. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  47760. }
  47761. }
  47762. };
  47763. PhysicsViewer.prototype.showImpostor = function (impostor) {
  47764. for (var i = 0; i < this._numMeshes; i++) {
  47765. if (this._impostors[i] == impostor) {
  47766. return;
  47767. }
  47768. }
  47769. var debugMesh = this._getDebugMesh(impostor, this._scene);
  47770. if (debugMesh) {
  47771. this._impostors[this._numMeshes] = impostor;
  47772. this._meshes[this._numMeshes] = debugMesh;
  47773. if (this._numMeshes === 0) {
  47774. this._renderFunction = this._updateDebugMeshes.bind(this);
  47775. this._scene.registerBeforeRender(this._renderFunction);
  47776. }
  47777. this._numMeshes++;
  47778. }
  47779. };
  47780. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  47781. var removed = false;
  47782. for (var i = 0; i < this._numMeshes; i++) {
  47783. if (this._impostors[i] == impostor) {
  47784. this._scene.removeMesh(this._meshes[i]);
  47785. this._meshes[i].dispose();
  47786. this._numMeshes--;
  47787. if (this._numMeshes > 0) {
  47788. this._meshes[i] = this._meshes[this._numMeshes];
  47789. this._impostors[i] = this._impostors[this._numMeshes];
  47790. this._meshes[this._numMeshes] = null;
  47791. this._impostors[this._numMeshes] = null;
  47792. }
  47793. else {
  47794. this._meshes[0] = null;
  47795. this._impostors[0] = null;
  47796. }
  47797. removed = true;
  47798. break;
  47799. }
  47800. }
  47801. if (removed && this._numMeshes === 0) {
  47802. this._scene.unregisterBeforeRender(this._renderFunction);
  47803. }
  47804. };
  47805. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  47806. if (!this._debugMaterial) {
  47807. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  47808. this._debugMaterial.wireframe = true;
  47809. }
  47810. return this._debugMaterial;
  47811. };
  47812. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  47813. if (!this._debugBoxMesh) {
  47814. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  47815. this._debugBoxMesh.renderingGroupId = 1;
  47816. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  47817. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  47818. scene.removeMesh(this._debugBoxMesh);
  47819. }
  47820. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  47821. };
  47822. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  47823. if (!this._debugSphereMesh) {
  47824. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  47825. this._debugSphereMesh.renderingGroupId = 1;
  47826. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  47827. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  47828. scene.removeMesh(this._debugSphereMesh);
  47829. }
  47830. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  47831. };
  47832. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  47833. var body = impostor.physicsBody;
  47834. var shape = body.shapes[0];
  47835. var mesh;
  47836. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  47837. mesh = this._getDebugBoxMesh(scene);
  47838. impostor.getBoxSizeToRef(mesh.scaling);
  47839. }
  47840. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  47841. mesh = this._getDebugSphereMesh(scene);
  47842. var radius = impostor.getRadius();
  47843. mesh.scaling.x = radius * 2;
  47844. mesh.scaling.y = radius * 2;
  47845. mesh.scaling.z = radius * 2;
  47846. }
  47847. return mesh;
  47848. };
  47849. PhysicsViewer.prototype.dispose = function () {
  47850. for (var i = 0; i < this._numMeshes; i++) {
  47851. this.hideImpostor(this._impostors[i]);
  47852. }
  47853. if (this._debugBoxMesh) {
  47854. this._debugBoxMesh.dispose();
  47855. }
  47856. if (this._debugSphereMesh) {
  47857. this._debugSphereMesh.dispose();
  47858. }
  47859. if (this._debugMaterial) {
  47860. this._debugMaterial.dispose();
  47861. }
  47862. this._impostors.length = 0;
  47863. this._scene = null;
  47864. this._physicsEnginePlugin = null;
  47865. };
  47866. return PhysicsViewer;
  47867. }());
  47868. Debug.PhysicsViewer = PhysicsViewer;
  47869. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47870. })(BABYLON || (BABYLON = {}));
  47871. //# sourceMappingURL=babylon.physicsViewer.js.map
  47872. var BABYLON;
  47873. (function (BABYLON) {
  47874. var BoundingBoxRenderer = (function () {
  47875. function BoundingBoxRenderer(scene) {
  47876. this.frontColor = new BABYLON.Color3(1, 1, 1);
  47877. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  47878. this.showBackLines = true;
  47879. this.renderList = new BABYLON.SmartArray(32);
  47880. this._vertexBuffers = {};
  47881. this._scene = scene;
  47882. }
  47883. BoundingBoxRenderer.prototype._prepareRessources = function () {
  47884. if (this._colorShader) {
  47885. return;
  47886. }
  47887. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  47888. attributes: [BABYLON.VertexBuffer.PositionKind],
  47889. uniforms: ["world", "viewProjection", "color"]
  47890. });
  47891. var engine = this._scene.getEngine();
  47892. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  47893. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  47894. this._createIndexBuffer();
  47895. };
  47896. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  47897. var engine = this._scene.getEngine();
  47898. 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]);
  47899. };
  47900. BoundingBoxRenderer.prototype._rebuild = function () {
  47901. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  47902. this._createIndexBuffer();
  47903. };
  47904. BoundingBoxRenderer.prototype.reset = function () {
  47905. this.renderList.reset();
  47906. };
  47907. BoundingBoxRenderer.prototype.render = function () {
  47908. if (this.renderList.length === 0) {
  47909. return;
  47910. }
  47911. this._prepareRessources();
  47912. if (!this._colorShader.isReady()) {
  47913. return;
  47914. }
  47915. var engine = this._scene.getEngine();
  47916. engine.setDepthWrite(false);
  47917. this._colorShader._preBind();
  47918. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  47919. var boundingBox = this.renderList.data[boundingBoxIndex];
  47920. var min = boundingBox.minimum;
  47921. var max = boundingBox.maximum;
  47922. var diff = max.subtract(min);
  47923. var median = min.add(diff.scale(0.5));
  47924. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  47925. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  47926. .multiply(boundingBox.getWorldMatrix());
  47927. // VBOs
  47928. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  47929. if (this.showBackLines) {
  47930. // Back
  47931. engine.setDepthFunctionToGreaterOrEqual();
  47932. this._scene.resetCachedMaterial();
  47933. this._colorShader.setColor4("color", this.backColor.toColor4());
  47934. this._colorShader.bind(worldMatrix);
  47935. // Draw order
  47936. engine.draw(false, 0, 24);
  47937. }
  47938. // Front
  47939. engine.setDepthFunctionToLess();
  47940. this._scene.resetCachedMaterial();
  47941. this._colorShader.setColor4("color", this.frontColor.toColor4());
  47942. this._colorShader.bind(worldMatrix);
  47943. // Draw order
  47944. engine.draw(false, 0, 24);
  47945. }
  47946. this._colorShader.unbind();
  47947. engine.setDepthFunctionToLessOrEqual();
  47948. engine.setDepthWrite(true);
  47949. };
  47950. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  47951. this._prepareRessources();
  47952. if (!this._colorShader.isReady()) {
  47953. return;
  47954. }
  47955. var engine = this._scene.getEngine();
  47956. engine.setDepthWrite(false);
  47957. engine.setColorWrite(false);
  47958. this._colorShader._preBind();
  47959. var boundingBox = mesh._boundingInfo.boundingBox;
  47960. var min = boundingBox.minimum;
  47961. var max = boundingBox.maximum;
  47962. var diff = max.subtract(min);
  47963. var median = min.add(diff.scale(0.5));
  47964. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  47965. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  47966. .multiply(boundingBox.getWorldMatrix());
  47967. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  47968. engine.setDepthFunctionToLess();
  47969. this._scene.resetCachedMaterial();
  47970. this._colorShader.bind(worldMatrix);
  47971. engine.draw(false, 0, 24);
  47972. this._colorShader.unbind();
  47973. engine.setDepthFunctionToLessOrEqual();
  47974. engine.setDepthWrite(true);
  47975. engine.setColorWrite(true);
  47976. };
  47977. BoundingBoxRenderer.prototype.dispose = function () {
  47978. if (!this._colorShader) {
  47979. return;
  47980. }
  47981. this.renderList.dispose();
  47982. this._colorShader.dispose();
  47983. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  47984. if (buffer) {
  47985. buffer.dispose();
  47986. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  47987. }
  47988. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47989. };
  47990. return BoundingBoxRenderer;
  47991. }());
  47992. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  47993. })(BABYLON || (BABYLON = {}));
  47994. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  47995. var BABYLON;
  47996. (function (BABYLON) {
  47997. var TextureTools = (function () {
  47998. function TextureTools() {
  47999. }
  48000. /**
  48001. * Uses the GPU to create a copy texture rescaled at a given size
  48002. * @param texture Texture to copy from
  48003. * @param width Desired width
  48004. * @param height Desired height
  48005. * @return Generated texture
  48006. */
  48007. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  48008. if (useBilinearMode === void 0) { useBilinearMode = true; }
  48009. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  48010. var scene = texture.getScene();
  48011. var engine = scene.getEngine();
  48012. rtt.wrapU = texture.wrapU;
  48013. rtt.wrapV = texture.wrapV;
  48014. rtt.uOffset = texture.uOffset;
  48015. rtt.vOffset = texture.vOffset;
  48016. rtt.uScale = texture.uScale;
  48017. rtt.vScale = texture.vScale;
  48018. rtt.uAng = texture.uAng;
  48019. rtt.vAng = texture.vAng;
  48020. rtt.wAng = texture.wAng;
  48021. rtt.coordinatesIndex = texture.coordinatesIndex;
  48022. rtt.level = texture.level;
  48023. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  48024. rtt._texture.isReady = false;
  48025. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48026. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48027. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48028. passPostProcess.getEffect().executeWhenCompiled(function () {
  48029. passPostProcess.onApply = function (effect) {
  48030. effect.setTexture("textureSampler", texture);
  48031. };
  48032. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  48033. engine.unBindFramebuffer(rtt.getInternalTexture());
  48034. rtt.disposeFramebufferObjects();
  48035. passPostProcess.dispose();
  48036. rtt._texture.isReady = true;
  48037. });
  48038. return rtt;
  48039. };
  48040. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  48041. if (!scene._environmentBRDFTexture) {
  48042. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48043. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48044. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48045. scene._environmentBRDFTexture = texture;
  48046. }
  48047. return scene._environmentBRDFTexture;
  48048. };
  48049. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  48050. return TextureTools;
  48051. }());
  48052. BABYLON.TextureTools = TextureTools;
  48053. })(BABYLON || (BABYLON = {}));
  48054. //# sourceMappingURL=babylon.textureTools.js.map
  48055. var BABYLON;
  48056. (function (BABYLON) {
  48057. var SphericalPolynomial = (function () {
  48058. function SphericalPolynomial() {
  48059. this.x = BABYLON.Vector3.Zero();
  48060. this.y = BABYLON.Vector3.Zero();
  48061. this.z = BABYLON.Vector3.Zero();
  48062. this.xx = BABYLON.Vector3.Zero();
  48063. this.yy = BABYLON.Vector3.Zero();
  48064. this.zz = BABYLON.Vector3.Zero();
  48065. this.xy = BABYLON.Vector3.Zero();
  48066. this.yz = BABYLON.Vector3.Zero();
  48067. this.zx = BABYLON.Vector3.Zero();
  48068. }
  48069. SphericalPolynomial.prototype.addAmbient = function (color) {
  48070. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  48071. this.xx = this.xx.add(colorVector);
  48072. this.yy = this.yy.add(colorVector);
  48073. this.zz = this.zz.add(colorVector);
  48074. };
  48075. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  48076. var result = new SphericalPolynomial();
  48077. result.x = harmonics.L11.scale(1.02333);
  48078. result.y = harmonics.L1_1.scale(1.02333);
  48079. result.z = harmonics.L10.scale(1.02333);
  48080. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  48081. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  48082. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  48083. result.yz = harmonics.L2_1.scale(0.858086);
  48084. result.zx = harmonics.L21.scale(0.858086);
  48085. result.xy = harmonics.L2_2.scale(0.858086);
  48086. result.scale(1.0 / Math.PI);
  48087. return result;
  48088. };
  48089. SphericalPolynomial.prototype.scale = function (scale) {
  48090. this.x = this.x.scale(scale);
  48091. this.y = this.y.scale(scale);
  48092. this.z = this.z.scale(scale);
  48093. this.xx = this.xx.scale(scale);
  48094. this.yy = this.yy.scale(scale);
  48095. this.zz = this.zz.scale(scale);
  48096. this.yz = this.yz.scale(scale);
  48097. this.zx = this.zx.scale(scale);
  48098. this.xy = this.xy.scale(scale);
  48099. };
  48100. return SphericalPolynomial;
  48101. }());
  48102. BABYLON.SphericalPolynomial = SphericalPolynomial;
  48103. var SphericalHarmonics = (function () {
  48104. function SphericalHarmonics() {
  48105. this.L00 = BABYLON.Vector3.Zero();
  48106. this.L1_1 = BABYLON.Vector3.Zero();
  48107. this.L10 = BABYLON.Vector3.Zero();
  48108. this.L11 = BABYLON.Vector3.Zero();
  48109. this.L2_2 = BABYLON.Vector3.Zero();
  48110. this.L2_1 = BABYLON.Vector3.Zero();
  48111. this.L20 = BABYLON.Vector3.Zero();
  48112. this.L21 = BABYLON.Vector3.Zero();
  48113. this.L22 = BABYLON.Vector3.Zero();
  48114. }
  48115. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  48116. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  48117. var c = colorVector.scale(deltaSolidAngle);
  48118. this.L00 = this.L00.add(c.scale(0.282095));
  48119. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  48120. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  48121. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  48122. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  48123. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  48124. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  48125. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  48126. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  48127. };
  48128. SphericalHarmonics.prototype.scale = function (scale) {
  48129. this.L00 = this.L00.scale(scale);
  48130. this.L1_1 = this.L1_1.scale(scale);
  48131. this.L10 = this.L10.scale(scale);
  48132. this.L11 = this.L11.scale(scale);
  48133. this.L2_2 = this.L2_2.scale(scale);
  48134. this.L2_1 = this.L2_1.scale(scale);
  48135. this.L20 = this.L20.scale(scale);
  48136. this.L21 = this.L21.scale(scale);
  48137. this.L22 = this.L22.scale(scale);
  48138. };
  48139. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  48140. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  48141. //
  48142. // E_lm = A_l * L_lm
  48143. //
  48144. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  48145. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  48146. // the scaling factors are given in equation 9.
  48147. // Constant (Band 0)
  48148. this.L00 = this.L00.scale(3.141593);
  48149. // Linear (Band 1)
  48150. this.L1_1 = this.L1_1.scale(2.094395);
  48151. this.L10 = this.L10.scale(2.094395);
  48152. this.L11 = this.L11.scale(2.094395);
  48153. // Quadratic (Band 2)
  48154. this.L2_2 = this.L2_2.scale(0.785398);
  48155. this.L2_1 = this.L2_1.scale(0.785398);
  48156. this.L20 = this.L20.scale(0.785398);
  48157. this.L21 = this.L21.scale(0.785398);
  48158. this.L22 = this.L22.scale(0.785398);
  48159. };
  48160. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  48161. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  48162. // L = (1/pi) * E * rho
  48163. //
  48164. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  48165. this.scale(1.0 / Math.PI);
  48166. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  48167. // (The pixel shader must apply albedo after texture fetches, etc).
  48168. };
  48169. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  48170. var result = new SphericalHarmonics();
  48171. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  48172. result.L1_1 = polynomial.y.scale(0.977204);
  48173. result.L10 = polynomial.z.scale(0.977204);
  48174. result.L11 = polynomial.x.scale(0.977204);
  48175. result.L2_2 = polynomial.xy.scale(1.16538);
  48176. result.L2_1 = polynomial.yz.scale(1.16538);
  48177. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  48178. result.L21 = polynomial.zx.scale(1.16538);
  48179. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  48180. result.scale(Math.PI);
  48181. return result;
  48182. };
  48183. return SphericalHarmonics;
  48184. }());
  48185. BABYLON.SphericalHarmonics = SphericalHarmonics;
  48186. })(BABYLON || (BABYLON = {}));
  48187. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  48188. var BABYLON;
  48189. (function (BABYLON) {
  48190. var Internals;
  48191. (function (Internals) {
  48192. var FileFaceOrientation = (function () {
  48193. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  48194. this.name = name;
  48195. this.worldAxisForNormal = worldAxisForNormal;
  48196. this.worldAxisForFileX = worldAxisForFileX;
  48197. this.worldAxisForFileY = worldAxisForFileY;
  48198. }
  48199. return FileFaceOrientation;
  48200. }());
  48201. ;
  48202. /**
  48203. * Helper class dealing with the extraction of spherical polynomial dataArray
  48204. * from a cube map.
  48205. */
  48206. var CubeMapToSphericalPolynomialTools = (function () {
  48207. function CubeMapToSphericalPolynomialTools() {
  48208. }
  48209. /**
  48210. * Converts a texture to the according Spherical Polynomial data.
  48211. * This extracts the first 3 orders only as they are the only one used in the lighting.
  48212. *
  48213. * @param texture The texture to extract the information from.
  48214. * @return The Spherical Polynomial data.
  48215. */
  48216. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  48217. if (!texture.isCube) {
  48218. // Only supports cube Textures currently.
  48219. return null;
  48220. }
  48221. var size = texture.getSize().width;
  48222. var right = texture.readPixels(0);
  48223. var left = texture.readPixels(1);
  48224. var up;
  48225. var down;
  48226. if (texture.isRenderTarget) {
  48227. up = texture.readPixels(3);
  48228. down = texture.readPixels(2);
  48229. }
  48230. else {
  48231. up = texture.readPixels(2);
  48232. down = texture.readPixels(3);
  48233. }
  48234. var front = texture.readPixels(4);
  48235. var back = texture.readPixels(5);
  48236. var gammaSpace = texture.gammaSpace;
  48237. // Always read as RGBA.
  48238. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  48239. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  48240. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  48241. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  48242. }
  48243. var cubeInfo = {
  48244. size: size,
  48245. right: right,
  48246. left: left,
  48247. up: up,
  48248. down: down,
  48249. front: front,
  48250. back: back,
  48251. format: format,
  48252. type: type,
  48253. gammaSpace: gammaSpace,
  48254. };
  48255. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  48256. };
  48257. /**
  48258. * Converts a cubemap to the according Spherical Polynomial data.
  48259. * This extracts the first 3 orders only as they are the only one used in the lighting.
  48260. *
  48261. * @param cubeInfo The Cube map to extract the information from.
  48262. * @return The Spherical Polynomial data.
  48263. */
  48264. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  48265. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  48266. var totalSolidAngle = 0.0;
  48267. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  48268. var du = 2.0 / cubeInfo.size;
  48269. var dv = du;
  48270. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  48271. var minUV = du * 0.5 - 1.0;
  48272. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48273. var fileFace = this.FileFaces[faceIndex];
  48274. var dataArray = cubeInfo[fileFace.name];
  48275. var v = minUV;
  48276. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  48277. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  48278. // Because SP is still linear, so summation is fine in that basis.
  48279. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  48280. for (var y = 0; y < cubeInfo.size; y++) {
  48281. var u = minUV;
  48282. for (var x = 0; x < cubeInfo.size; x++) {
  48283. // World direction (not normalised)
  48284. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  48285. worldDirection.normalize();
  48286. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  48287. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  48288. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  48289. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  48290. // Handle Integer types.
  48291. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  48292. r /= 255;
  48293. g /= 255;
  48294. b /= 255;
  48295. }
  48296. // Handle Gamma space textures.
  48297. if (cubeInfo.gammaSpace) {
  48298. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  48299. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  48300. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  48301. }
  48302. var color = new BABYLON.Color3(r, g, b);
  48303. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48304. totalSolidAngle += deltaSolidAngle;
  48305. u += du;
  48306. }
  48307. v += dv;
  48308. }
  48309. }
  48310. // Solid angle for entire sphere is 4*pi
  48311. var sphereSolidAngle = 4.0 * Math.PI;
  48312. // Adjust the solid angle to allow for how many faces we processed.
  48313. var facesProcessed = 6.0;
  48314. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  48315. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  48316. // This is needed because the numerical integration over the cube uses a
  48317. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  48318. // and also to compensate for accumulative error due to float precision in the summation.
  48319. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  48320. sphericalHarmonics.scale(correctionFactor);
  48321. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  48322. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  48323. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  48324. };
  48325. CubeMapToSphericalPolynomialTools.FileFaces = [
  48326. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  48327. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  48328. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  48329. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  48330. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  48331. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  48332. ];
  48333. return CubeMapToSphericalPolynomialTools;
  48334. }());
  48335. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  48336. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48337. })(BABYLON || (BABYLON = {}));
  48338. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  48339. var BABYLON;
  48340. (function (BABYLON) {
  48341. var Internals;
  48342. (function (Internals) {
  48343. /**
  48344. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  48345. */
  48346. var PanoramaToCubeMapTools = (function () {
  48347. function PanoramaToCubeMapTools() {
  48348. }
  48349. /**
  48350. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  48351. *
  48352. * @param float32Array The source data.
  48353. * @param inputWidth The width of the input panorama.
  48354. * @param inputhHeight The height of the input panorama.
  48355. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  48356. * @return The cubemap data
  48357. */
  48358. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  48359. if (!float32Array) {
  48360. throw "ConvertPanoramaToCubemap: input cannot be null";
  48361. }
  48362. if (float32Array.length != inputWidth * inputHeight * 3) {
  48363. throw "ConvertPanoramaToCubemap: input size is wrong";
  48364. }
  48365. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  48366. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  48367. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  48368. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  48369. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  48370. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  48371. return {
  48372. front: textureFront,
  48373. back: textureBack,
  48374. left: textureLeft,
  48375. right: textureRight,
  48376. up: textureUp,
  48377. down: textureDown,
  48378. size: size,
  48379. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  48380. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  48381. gammaSpace: false,
  48382. };
  48383. };
  48384. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  48385. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  48386. var textureArray = new Float32Array(buffer);
  48387. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  48388. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  48389. var dy = 1 / texSize;
  48390. var fy = 0;
  48391. for (var y = 0; y < texSize; y++) {
  48392. var xv1 = faceData[0];
  48393. var xv2 = faceData[2];
  48394. for (var x = 0; x < texSize; x++) {
  48395. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  48396. v.normalize();
  48397. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  48398. // 3 channels per pixels
  48399. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  48400. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  48401. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  48402. xv1 = xv1.add(rotDX1);
  48403. xv2 = xv2.add(rotDX2);
  48404. }
  48405. fy += dy;
  48406. }
  48407. return textureArray;
  48408. };
  48409. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  48410. var theta = Math.atan2(vDir.z, vDir.x);
  48411. var phi = Math.acos(vDir.y);
  48412. while (theta < -Math.PI)
  48413. theta += 2 * Math.PI;
  48414. while (theta > Math.PI)
  48415. theta -= 2 * Math.PI;
  48416. var dx = theta / Math.PI;
  48417. var dy = phi / Math.PI;
  48418. // recenter.
  48419. dx = dx * 0.5 + 0.5;
  48420. var px = Math.round(dx * inputWidth);
  48421. if (px < 0)
  48422. px = 0;
  48423. else if (px >= inputWidth)
  48424. px = inputWidth - 1;
  48425. var py = Math.round(dy * inputHeight);
  48426. if (py < 0)
  48427. py = 0;
  48428. else if (py >= inputHeight)
  48429. py = inputHeight - 1;
  48430. var inputY = (inputHeight - py - 1);
  48431. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  48432. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  48433. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  48434. return {
  48435. r: r,
  48436. g: g,
  48437. b: b
  48438. };
  48439. };
  48440. PanoramaToCubeMapTools.FACE_FRONT = [
  48441. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48442. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48443. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48444. new BABYLON.Vector3(1.0, 1.0, -1.0)
  48445. ];
  48446. PanoramaToCubeMapTools.FACE_BACK = [
  48447. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48448. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48449. new BABYLON.Vector3(1.0, 1.0, 1.0),
  48450. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  48451. ];
  48452. PanoramaToCubeMapTools.FACE_RIGHT = [
  48453. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48454. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48455. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48456. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48457. ];
  48458. PanoramaToCubeMapTools.FACE_LEFT = [
  48459. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48460. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48461. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48462. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  48463. ];
  48464. PanoramaToCubeMapTools.FACE_DOWN = [
  48465. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48466. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48467. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48468. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48469. ];
  48470. PanoramaToCubeMapTools.FACE_UP = [
  48471. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48472. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48473. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48474. new BABYLON.Vector3(1.0, -1.0, -1.0)
  48475. ];
  48476. return PanoramaToCubeMapTools;
  48477. }());
  48478. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  48479. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48480. })(BABYLON || (BABYLON = {}));
  48481. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  48482. var BABYLON;
  48483. (function (BABYLON) {
  48484. var Internals;
  48485. (function (Internals) {
  48486. ;
  48487. /**
  48488. * This groups tools to convert HDR texture to native colors array.
  48489. */
  48490. var HDRTools = (function () {
  48491. function HDRTools() {
  48492. }
  48493. HDRTools.Ldexp = function (mantissa, exponent) {
  48494. if (exponent > 1023) {
  48495. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  48496. }
  48497. if (exponent < -1074) {
  48498. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  48499. }
  48500. return mantissa * Math.pow(2, exponent);
  48501. };
  48502. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  48503. if (exponent > 0) {
  48504. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  48505. float32array[index + 0] = red * exponent;
  48506. float32array[index + 1] = green * exponent;
  48507. float32array[index + 2] = blue * exponent;
  48508. }
  48509. else {
  48510. float32array[index + 0] = 0;
  48511. float32array[index + 1] = 0;
  48512. float32array[index + 2] = 0;
  48513. }
  48514. };
  48515. HDRTools.readStringLine = function (uint8array, startIndex) {
  48516. var line = "";
  48517. var character = "";
  48518. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  48519. character = String.fromCharCode(uint8array[i]);
  48520. if (character == "\n") {
  48521. break;
  48522. }
  48523. line += character;
  48524. }
  48525. return line;
  48526. };
  48527. /**
  48528. * Reads header information from an RGBE texture stored in a native array.
  48529. * More information on this format are available here:
  48530. * https://en.wikipedia.org/wiki/RGBE_image_format
  48531. *
  48532. * @param uint8array The binary file stored in native array.
  48533. * @return The header information.
  48534. */
  48535. HDRTools.RGBE_ReadHeader = function (uint8array) {
  48536. var height = 0;
  48537. var width = 0;
  48538. var line = this.readStringLine(uint8array, 0);
  48539. if (line[0] != '#' || line[1] != '?') {
  48540. throw "Bad HDR Format.";
  48541. }
  48542. var endOfHeader = false;
  48543. var findFormat = false;
  48544. var lineIndex = 0;
  48545. do {
  48546. lineIndex += (line.length + 1);
  48547. line = this.readStringLine(uint8array, lineIndex);
  48548. if (line == "FORMAT=32-bit_rle_rgbe") {
  48549. findFormat = true;
  48550. }
  48551. else if (line.length == 0) {
  48552. endOfHeader = true;
  48553. }
  48554. } while (!endOfHeader);
  48555. if (!findFormat) {
  48556. throw "HDR Bad header format, unsupported FORMAT";
  48557. }
  48558. lineIndex += (line.length + 1);
  48559. line = this.readStringLine(uint8array, lineIndex);
  48560. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  48561. var match = sizeRegexp.exec(line);
  48562. // TODO. Support +Y and -X if needed.
  48563. if (match.length < 3) {
  48564. throw "HDR Bad header format, no size";
  48565. }
  48566. width = parseInt(match[2]);
  48567. height = parseInt(match[1]);
  48568. if (width < 8 || width > 0x7fff) {
  48569. throw "HDR Bad header format, unsupported size";
  48570. }
  48571. lineIndex += (line.length + 1);
  48572. return {
  48573. height: height,
  48574. width: width,
  48575. dataPosition: lineIndex
  48576. };
  48577. };
  48578. /**
  48579. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  48580. * This RGBE texture needs to store the information as a panorama.
  48581. *
  48582. * More information on this format are available here:
  48583. * https://en.wikipedia.org/wiki/RGBE_image_format
  48584. *
  48585. * @param buffer The binary file stored in an array buffer.
  48586. * @param size The expected size of the extracted cubemap.
  48587. * @return The Cube Map information.
  48588. */
  48589. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  48590. var uint8array = new Uint8Array(buffer);
  48591. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  48592. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48593. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  48594. return cubeMapData;
  48595. };
  48596. /**
  48597. * Returns the pixels data extracted from an RGBE texture.
  48598. * This pixels will be stored left to right up to down in the R G B order in one array.
  48599. *
  48600. * More information on this format are available here:
  48601. * https://en.wikipedia.org/wiki/RGBE_image_format
  48602. *
  48603. * @param uint8array The binary file stored in an array buffer.
  48604. * @param hdrInfo The header information of the file.
  48605. * @return The pixels data in RGB right to left up to down order.
  48606. */
  48607. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  48608. // Keep for multi format supports.
  48609. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48610. };
  48611. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  48612. var num_scanlines = hdrInfo.height;
  48613. var scanline_width = hdrInfo.width;
  48614. var a, b, c, d, count;
  48615. var dataIndex = hdrInfo.dataPosition;
  48616. var index = 0, endIndex = 0, i = 0;
  48617. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  48618. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  48619. // 3 channels of 4 bytes per pixel in float.
  48620. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  48621. var resultArray = new Float32Array(resultBuffer);
  48622. // read in each successive scanline
  48623. while (num_scanlines > 0) {
  48624. a = uint8array[dataIndex++];
  48625. b = uint8array[dataIndex++];
  48626. c = uint8array[dataIndex++];
  48627. d = uint8array[dataIndex++];
  48628. if (a != 2 || b != 2 || (c & 0x80)) {
  48629. // this file is not run length encoded
  48630. throw "HDR Bad header format, not RLE";
  48631. }
  48632. if (((c << 8) | d) != scanline_width) {
  48633. throw "HDR Bad header format, wrong scan line width";
  48634. }
  48635. index = 0;
  48636. // read each of the four channels for the scanline into the buffer
  48637. for (i = 0; i < 4; i++) {
  48638. endIndex = (i + 1) * scanline_width;
  48639. while (index < endIndex) {
  48640. a = uint8array[dataIndex++];
  48641. b = uint8array[dataIndex++];
  48642. if (a > 128) {
  48643. // a run of the same value
  48644. count = a - 128;
  48645. if ((count == 0) || (count > endIndex - index)) {
  48646. throw "HDR Bad Format, bad scanline data (run)";
  48647. }
  48648. while (count-- > 0) {
  48649. scanLineArray[index++] = b;
  48650. }
  48651. }
  48652. else {
  48653. // a non-run
  48654. count = a;
  48655. if ((count == 0) || (count > endIndex - index)) {
  48656. throw "HDR Bad Format, bad scanline data (non-run)";
  48657. }
  48658. scanLineArray[index++] = b;
  48659. if (--count > 0) {
  48660. for (var j = 0; j < count; j++) {
  48661. scanLineArray[index++] = uint8array[dataIndex++];
  48662. }
  48663. }
  48664. }
  48665. }
  48666. }
  48667. // now convert data from buffer into floats
  48668. for (i = 0; i < scanline_width; i++) {
  48669. a = scanLineArray[i];
  48670. b = scanLineArray[i + scanline_width];
  48671. c = scanLineArray[i + 2 * scanline_width];
  48672. d = scanLineArray[i + 3 * scanline_width];
  48673. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  48674. }
  48675. num_scanlines--;
  48676. }
  48677. return resultArray;
  48678. };
  48679. return HDRTools;
  48680. }());
  48681. Internals.HDRTools = HDRTools;
  48682. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48683. })(BABYLON || (BABYLON = {}));
  48684. //# sourceMappingURL=babylon.hdr.js.map
  48685. var BABYLON;
  48686. (function (BABYLON) {
  48687. /**
  48688. * This represents a texture coming from an HDR input.
  48689. *
  48690. * The only supported format is currently panorama picture stored in RGBE format.
  48691. * Example of such files can be found on HDRLib: http://hdrlib.com/
  48692. */
  48693. var HDRCubeTexture = (function (_super) {
  48694. __extends(HDRCubeTexture, _super);
  48695. /**
  48696. * Instantiates an HDRTexture from the following parameters.
  48697. *
  48698. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  48699. * @param scene The scene the texture will be used in
  48700. * @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.
  48701. * @param noMipmap Forces to not generate the mipmap if true
  48702. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  48703. * @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)
  48704. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  48705. */
  48706. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  48707. if (noMipmap === void 0) { noMipmap = false; }
  48708. if (generateHarmonics === void 0) { generateHarmonics = true; }
  48709. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  48710. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  48711. if (onLoad === void 0) { onLoad = null; }
  48712. if (onError === void 0) { onError = null; }
  48713. var _this = _super.call(this, scene) || this;
  48714. _this._useInGammaSpace = false;
  48715. _this._generateHarmonics = true;
  48716. _this._isBABYLONPreprocessed = false;
  48717. _this._onLoad = null;
  48718. _this._onError = null;
  48719. /**
  48720. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  48721. */
  48722. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  48723. /**
  48724. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  48725. * This is usefull at run time to apply the good shader.
  48726. */
  48727. _this.isPMREM = false;
  48728. _this._isBlocking = true;
  48729. if (!url) {
  48730. return _this;
  48731. }
  48732. _this.name = url;
  48733. _this.url = url;
  48734. _this.hasAlpha = false;
  48735. _this.isCube = true;
  48736. _this._textureMatrix = BABYLON.Matrix.Identity();
  48737. _this._onLoad = onLoad;
  48738. _this._onError = onError;
  48739. _this.gammaSpace = false;
  48740. if (size) {
  48741. _this._isBABYLONPreprocessed = false;
  48742. _this._noMipmap = noMipmap;
  48743. _this._size = size;
  48744. _this._useInGammaSpace = useInGammaSpace;
  48745. _this._usePMREMGenerator = usePMREMGenerator &&
  48746. scene.getEngine().getCaps().textureLOD &&
  48747. _this.getScene().getEngine().getCaps().textureFloat &&
  48748. !_this._useInGammaSpace;
  48749. }
  48750. else {
  48751. _this._isBABYLONPreprocessed = true;
  48752. _this._noMipmap = false;
  48753. _this._useInGammaSpace = false;
  48754. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  48755. _this.getScene().getEngine().getCaps().textureFloat &&
  48756. !_this._useInGammaSpace;
  48757. }
  48758. _this.isPMREM = _this._usePMREMGenerator;
  48759. _this._texture = _this._getFromCache(url, _this._noMipmap);
  48760. if (!_this._texture) {
  48761. if (!scene.useDelayedTextureLoading) {
  48762. _this.loadTexture();
  48763. }
  48764. else {
  48765. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  48766. }
  48767. }
  48768. return _this;
  48769. }
  48770. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  48771. /**
  48772. * Gets wether or not the texture is blocking during loading.
  48773. */
  48774. get: function () {
  48775. return this._isBlocking;
  48776. },
  48777. /**
  48778. * Sets wether or not the texture is blocking during loading.
  48779. */
  48780. set: function (value) {
  48781. this._isBlocking = value;
  48782. },
  48783. enumerable: true,
  48784. configurable: true
  48785. });
  48786. /**
  48787. * Occurs when the file is a preprocessed .babylon.hdr file.
  48788. */
  48789. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  48790. var _this = this;
  48791. var mipLevels = 0;
  48792. var floatArrayView = null;
  48793. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  48794. var mips = [];
  48795. var startIndex = 30;
  48796. for (var level = 0; level < mipLevels; level++) {
  48797. mips.push([]);
  48798. // Fill each pixel of the mip level.
  48799. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  48800. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48801. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  48802. mips[level].push(faceData);
  48803. startIndex += faceSize;
  48804. }
  48805. }
  48806. return mips;
  48807. } : null;
  48808. var callback = function (buffer) {
  48809. // Create Native Array Views
  48810. var intArrayView = new Int32Array(buffer);
  48811. floatArrayView = new Float32Array(buffer);
  48812. // Fill header.
  48813. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  48814. _this._size = intArrayView[1]; // CubeMap max mip face size.
  48815. // Update Texture Information.
  48816. _this._texture.updateSize(_this._size, _this._size);
  48817. // Fill polynomial information.
  48818. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  48819. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  48820. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  48821. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  48822. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  48823. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  48824. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  48825. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  48826. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  48827. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  48828. _this.sphericalPolynomial = sphericalPolynomial;
  48829. // Fill pixel data.
  48830. mipLevels = intArrayView[29]; // Number of mip levels.
  48831. var startIndex = 30;
  48832. var data = [];
  48833. var faceSize = Math.pow(_this._size, 2) * 3;
  48834. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48835. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  48836. startIndex += faceSize;
  48837. }
  48838. var results = [];
  48839. var byteArray = null;
  48840. // Push each faces.
  48841. for (var k = 0; k < 6; k++) {
  48842. var dataFace = null;
  48843. // To be deprecated.
  48844. if (version === 1) {
  48845. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  48846. dataFace = data[j];
  48847. }
  48848. // If special cases.
  48849. if (!mipmapGenerator) {
  48850. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  48851. // 3 channels of 1 bytes per pixel in bytes.
  48852. var byteBuffer = new ArrayBuffer(faceSize);
  48853. byteArray = new Uint8Array(byteBuffer);
  48854. }
  48855. for (var i = 0; i < _this._size * _this._size; i++) {
  48856. // Put in gamma space if requested.
  48857. if (_this._useInGammaSpace) {
  48858. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  48859. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  48860. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  48861. }
  48862. // Convert to int texture for fallback.
  48863. if (byteArray) {
  48864. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  48865. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  48866. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  48867. // May use luminance instead if the result is not accurate.
  48868. var max = Math.max(Math.max(r, g), b);
  48869. if (max > 255) {
  48870. var scale = 255 / max;
  48871. r *= scale;
  48872. g *= scale;
  48873. b *= scale;
  48874. }
  48875. byteArray[(i * 3) + 0] = r;
  48876. byteArray[(i * 3) + 1] = g;
  48877. byteArray[(i * 3) + 2] = b;
  48878. }
  48879. }
  48880. }
  48881. // Fill the array accordingly.
  48882. if (byteArray) {
  48883. results.push(byteArray);
  48884. }
  48885. else {
  48886. results.push(dataFace);
  48887. }
  48888. }
  48889. return results;
  48890. };
  48891. 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);
  48892. };
  48893. /**
  48894. * Occurs when the file is raw .hdr file.
  48895. */
  48896. HDRCubeTexture.prototype.loadHDRTexture = function () {
  48897. var _this = this;
  48898. var callback = function (buffer) {
  48899. // Extract the raw linear data.
  48900. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  48901. // Generate harmonics if needed.
  48902. if (_this._generateHarmonics) {
  48903. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  48904. _this.sphericalPolynomial = sphericalPolynomial;
  48905. }
  48906. var results = [];
  48907. var byteArray = null;
  48908. // Push each faces.
  48909. for (var j = 0; j < 6; j++) {
  48910. // Create uintarray fallback.
  48911. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  48912. // 3 channels of 1 bytes per pixel in bytes.
  48913. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  48914. byteArray = new Uint8Array(byteBuffer);
  48915. }
  48916. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  48917. // If special cases.
  48918. if (_this._useInGammaSpace || byteArray) {
  48919. for (var i = 0; i < _this._size * _this._size; i++) {
  48920. // Put in gamma space if requested.
  48921. if (_this._useInGammaSpace) {
  48922. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  48923. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  48924. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  48925. }
  48926. // Convert to int texture for fallback.
  48927. if (byteArray) {
  48928. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  48929. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  48930. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  48931. // May use luminance instead if the result is not accurate.
  48932. var max = Math.max(Math.max(r, g), b);
  48933. if (max > 255) {
  48934. var scale = 255 / max;
  48935. r *= scale;
  48936. g *= scale;
  48937. b *= scale;
  48938. }
  48939. byteArray[(i * 3) + 0] = r;
  48940. byteArray[(i * 3) + 1] = g;
  48941. byteArray[(i * 3) + 2] = b;
  48942. }
  48943. }
  48944. }
  48945. if (byteArray) {
  48946. results.push(byteArray);
  48947. }
  48948. else {
  48949. results.push(dataFace);
  48950. }
  48951. }
  48952. return results;
  48953. };
  48954. var mipmapGenerator = null;
  48955. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  48956. // if (!this._noMipmap &&
  48957. // this._usePMREMGenerator) {
  48958. // mipmapGenerator = (data: ArrayBufferView[]) => {
  48959. // // Custom setup of the generator matching with the PBR shader values.
  48960. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  48961. // this._size,
  48962. // this._size,
  48963. // 0,
  48964. // 3,
  48965. // this.getScene().getEngine().getCaps().textureFloat,
  48966. // 2048,
  48967. // 0.25,
  48968. // false,
  48969. // true);
  48970. // return generator.filterCubeMap();
  48971. // };
  48972. // }
  48973. 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);
  48974. };
  48975. /**
  48976. * Starts the loading process of the texture.
  48977. */
  48978. HDRCubeTexture.prototype.loadTexture = function () {
  48979. if (this._isBABYLONPreprocessed) {
  48980. this.loadBabylonTexture();
  48981. }
  48982. else {
  48983. this.loadHDRTexture();
  48984. }
  48985. };
  48986. HDRCubeTexture.prototype.clone = function () {
  48987. var size = this._isBABYLONPreprocessed ? null : this._size;
  48988. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  48989. // Base texture
  48990. newTexture.level = this.level;
  48991. newTexture.wrapU = this.wrapU;
  48992. newTexture.wrapV = this.wrapV;
  48993. newTexture.coordinatesIndex = this.coordinatesIndex;
  48994. newTexture.coordinatesMode = this.coordinatesMode;
  48995. return newTexture;
  48996. };
  48997. // Methods
  48998. HDRCubeTexture.prototype.delayLoad = function () {
  48999. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  49000. return;
  49001. }
  49002. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49003. this._texture = this._getFromCache(this.url, this._noMipmap);
  49004. if (!this._texture) {
  49005. this.loadTexture();
  49006. }
  49007. };
  49008. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  49009. return this._textureMatrix;
  49010. };
  49011. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49012. this._textureMatrix = value;
  49013. };
  49014. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49015. var texture = null;
  49016. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  49017. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  49018. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  49019. texture.name = parsedTexture.name;
  49020. texture.hasAlpha = parsedTexture.hasAlpha;
  49021. texture.level = parsedTexture.level;
  49022. texture.coordinatesMode = parsedTexture.coordinatesMode;
  49023. texture.isBlocking = parsedTexture.isBlocking;
  49024. }
  49025. return texture;
  49026. };
  49027. HDRCubeTexture.prototype.serialize = function () {
  49028. if (!this.name) {
  49029. return null;
  49030. }
  49031. var serializationObject = {};
  49032. serializationObject.name = this.name;
  49033. serializationObject.hasAlpha = this.hasAlpha;
  49034. serializationObject.isCube = true;
  49035. serializationObject.level = this.level;
  49036. serializationObject.size = this._size;
  49037. serializationObject.coordinatesMode = this.coordinatesMode;
  49038. serializationObject.useInGammaSpace = this._useInGammaSpace;
  49039. serializationObject.generateHarmonics = this._generateHarmonics;
  49040. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  49041. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  49042. serializationObject.customType = "BABYLON.HDRCubeTexture";
  49043. serializationObject.noMipmap = this._noMipmap;
  49044. serializationObject.isBlocking = this._isBlocking;
  49045. return serializationObject;
  49046. };
  49047. /**
  49048. * Saves as a file the data contained in the texture in a binary format.
  49049. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  49050. * as the spherical used in the lighting.
  49051. * @param url The HDR file url.
  49052. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  49053. * @param onError Method called if any error happens during download.
  49054. * @return The packed binary data.
  49055. */
  49056. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  49057. if (onError === void 0) { onError = null; }
  49058. var callback = function (buffer) {
  49059. var data = new Blob([buffer], { type: 'application/octet-stream' });
  49060. // Returns a URL you can use as a href.
  49061. var objUrl = window.URL.createObjectURL(data);
  49062. // Simulates a link to it and click to dowload.
  49063. var a = document.createElement("a");
  49064. document.body.appendChild(a);
  49065. a.style.display = "none";
  49066. a.href = objUrl;
  49067. a.download = "envmap.babylon.hdr";
  49068. a.click();
  49069. };
  49070. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  49071. };
  49072. /**
  49073. * Serializes the data contained in the texture in a binary format.
  49074. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  49075. * as the spherical used in the lighting.
  49076. * @param url The HDR file url.
  49077. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  49078. * @param onError Method called if any error happens during download.
  49079. * @return The packed binary data.
  49080. */
  49081. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  49082. if (onError === void 0) { onError = null; }
  49083. // Needs the url tho create the texture.
  49084. if (!url) {
  49085. return null;
  49086. }
  49087. // Check Power of two size.
  49088. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  49089. return null;
  49090. }
  49091. // Coming Back in 3.1.
  49092. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  49093. return null;
  49094. };
  49095. HDRCubeTexture._facesMapping = [
  49096. "right",
  49097. "left",
  49098. "up",
  49099. "down",
  49100. "front",
  49101. "back"
  49102. ];
  49103. return HDRCubeTexture;
  49104. }(BABYLON.BaseTexture));
  49105. BABYLON.HDRCubeTexture = HDRCubeTexture;
  49106. })(BABYLON || (BABYLON = {}));
  49107. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  49108. var BABYLON;
  49109. (function (BABYLON) {
  49110. var DefaultLoadingScreen = (function () {
  49111. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  49112. if (_loadingText === void 0) { _loadingText = ""; }
  49113. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  49114. var _this = this;
  49115. this._renderingCanvas = _renderingCanvas;
  49116. this._loadingText = _loadingText;
  49117. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  49118. // Resize
  49119. this._resizeLoadingUI = function () {
  49120. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  49121. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  49122. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  49123. _this._loadingDiv.style.left = canvasRect.left + "px";
  49124. _this._loadingDiv.style.top = canvasRect.top + "px";
  49125. _this._loadingDiv.style.width = canvasRect.width + "px";
  49126. _this._loadingDiv.style.height = canvasRect.height + "px";
  49127. };
  49128. }
  49129. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  49130. if (this._loadingDiv) {
  49131. // Do not add a loading screen if there is already one
  49132. return;
  49133. }
  49134. this._loadingDiv = document.createElement("div");
  49135. this._loadingDiv.id = "babylonjsLoadingDiv";
  49136. this._loadingDiv.style.opacity = "0";
  49137. this._loadingDiv.style.transition = "opacity 1.5s ease";
  49138. // Loading text
  49139. this._loadingTextDiv = document.createElement("div");
  49140. this._loadingTextDiv.style.position = "absolute";
  49141. this._loadingTextDiv.style.left = "0";
  49142. this._loadingTextDiv.style.top = "50%";
  49143. this._loadingTextDiv.style.marginTop = "80px";
  49144. this._loadingTextDiv.style.width = "100%";
  49145. this._loadingTextDiv.style.height = "20px";
  49146. this._loadingTextDiv.style.fontFamily = "Arial";
  49147. this._loadingTextDiv.style.fontSize = "14px";
  49148. this._loadingTextDiv.style.color = "white";
  49149. this._loadingTextDiv.style.textAlign = "center";
  49150. this._loadingTextDiv.innerHTML = "Loading";
  49151. this._loadingDiv.appendChild(this._loadingTextDiv);
  49152. //set the predefined text
  49153. this._loadingTextDiv.innerHTML = this._loadingText;
  49154. // Generating keyframes
  49155. var style = document.createElement('style');
  49156. style.type = 'text/css';
  49157. 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 }";
  49158. style.innerHTML = keyFrames;
  49159. document.getElementsByTagName('head')[0].appendChild(style);
  49160. // Loading img
  49161. var imgBack = new Image();
  49162. 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";
  49163. imgBack.style.position = "absolute";
  49164. imgBack.style.left = "50%";
  49165. imgBack.style.top = "50%";
  49166. imgBack.style.marginLeft = "-60px";
  49167. imgBack.style.marginTop = "-60px";
  49168. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  49169. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  49170. imgBack.style.transformOrigin = "50% 50%";
  49171. imgBack.style.webkitTransformOrigin = "50% 50%";
  49172. this._loadingDiv.appendChild(imgBack);
  49173. this._resizeLoadingUI();
  49174. window.addEventListener("resize", this._resizeLoadingUI);
  49175. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  49176. document.body.appendChild(this._loadingDiv);
  49177. this._loadingDiv.style.opacity = "1";
  49178. };
  49179. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  49180. var _this = this;
  49181. if (!this._loadingDiv) {
  49182. return;
  49183. }
  49184. var onTransitionEnd = function () {
  49185. if (!_this._loadingDiv) {
  49186. return;
  49187. }
  49188. document.body.removeChild(_this._loadingDiv);
  49189. window.removeEventListener("resize", _this._resizeLoadingUI);
  49190. _this._loadingDiv = null;
  49191. };
  49192. this._loadingDiv.style.opacity = "0";
  49193. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  49194. };
  49195. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  49196. set: function (text) {
  49197. this._loadingText = text;
  49198. if (this._loadingTextDiv) {
  49199. this._loadingTextDiv.innerHTML = this._loadingText;
  49200. }
  49201. },
  49202. enumerable: true,
  49203. configurable: true
  49204. });
  49205. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  49206. get: function () {
  49207. return this._loadingDivBackgroundColor;
  49208. },
  49209. set: function (color) {
  49210. this._loadingDivBackgroundColor = color;
  49211. if (!this._loadingDiv) {
  49212. return;
  49213. }
  49214. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  49215. },
  49216. enumerable: true,
  49217. configurable: true
  49218. });
  49219. return DefaultLoadingScreen;
  49220. }());
  49221. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  49222. })(BABYLON || (BABYLON = {}));
  49223. //# sourceMappingURL=babylon.loadingScreen.js.map
  49224. var BABYLON;
  49225. (function (BABYLON) {
  49226. var SceneLoader = (function () {
  49227. function SceneLoader() {
  49228. }
  49229. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  49230. get: function () {
  49231. return 0;
  49232. },
  49233. enumerable: true,
  49234. configurable: true
  49235. });
  49236. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  49237. get: function () {
  49238. return 1;
  49239. },
  49240. enumerable: true,
  49241. configurable: true
  49242. });
  49243. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  49244. get: function () {
  49245. return 2;
  49246. },
  49247. enumerable: true,
  49248. configurable: true
  49249. });
  49250. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  49251. get: function () {
  49252. return 3;
  49253. },
  49254. enumerable: true,
  49255. configurable: true
  49256. });
  49257. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  49258. get: function () {
  49259. return SceneLoader._ForceFullSceneLoadingForIncremental;
  49260. },
  49261. set: function (value) {
  49262. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  49263. },
  49264. enumerable: true,
  49265. configurable: true
  49266. });
  49267. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  49268. get: function () {
  49269. return SceneLoader._ShowLoadingScreen;
  49270. },
  49271. set: function (value) {
  49272. SceneLoader._ShowLoadingScreen = value;
  49273. },
  49274. enumerable: true,
  49275. configurable: true
  49276. });
  49277. Object.defineProperty(SceneLoader, "loggingLevel", {
  49278. get: function () {
  49279. return SceneLoader._loggingLevel;
  49280. },
  49281. set: function (value) {
  49282. SceneLoader._loggingLevel = value;
  49283. },
  49284. enumerable: true,
  49285. configurable: true
  49286. });
  49287. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  49288. get: function () {
  49289. return SceneLoader._CleanBoneMatrixWeights;
  49290. },
  49291. set: function (value) {
  49292. SceneLoader._CleanBoneMatrixWeights = value;
  49293. },
  49294. enumerable: true,
  49295. configurable: true
  49296. });
  49297. SceneLoader._getDefaultPlugin = function () {
  49298. return SceneLoader._registeredPlugins[".babylon"];
  49299. };
  49300. SceneLoader._getPluginForExtension = function (extension) {
  49301. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  49302. if (registeredPlugin) {
  49303. return registeredPlugin;
  49304. }
  49305. return SceneLoader._getDefaultPlugin();
  49306. };
  49307. SceneLoader._getPluginForDirectLoad = function (data) {
  49308. for (var extension in SceneLoader._registeredPlugins) {
  49309. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  49310. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  49311. return SceneLoader._registeredPlugins[extension];
  49312. }
  49313. }
  49314. return SceneLoader._getDefaultPlugin();
  49315. };
  49316. SceneLoader._getPluginForFilename = function (sceneFilename) {
  49317. if (sceneFilename.name) {
  49318. sceneFilename = sceneFilename.name;
  49319. }
  49320. var dotPosition = sceneFilename.lastIndexOf(".");
  49321. var queryStringPosition = sceneFilename.indexOf("?");
  49322. if (queryStringPosition === -1) {
  49323. queryStringPosition = sceneFilename.length;
  49324. }
  49325. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  49326. return SceneLoader._getPluginForExtension(extension);
  49327. };
  49328. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  49329. SceneLoader._getDirectLoad = function (sceneFilename) {
  49330. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  49331. return sceneFilename.substr(5);
  49332. }
  49333. return null;
  49334. };
  49335. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49336. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  49337. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  49338. var plugin = registeredPlugin.plugin;
  49339. var useArrayBuffer = registeredPlugin.isBinary;
  49340. var database;
  49341. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  49342. var dataCallback = function (data) {
  49343. if (scene.isDisposed) {
  49344. onError("Scene has been disposed");
  49345. return;
  49346. }
  49347. scene.database = database;
  49348. try {
  49349. onSuccess(plugin, data);
  49350. }
  49351. catch (e) {
  49352. onError(null, e);
  49353. }
  49354. };
  49355. var manifestChecked = function (success) {
  49356. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  49357. onError(request.status + " " + request.statusText);
  49358. });
  49359. };
  49360. if (directLoad) {
  49361. dataCallback(directLoad);
  49362. return;
  49363. }
  49364. if (rootUrl.indexOf("file:") === -1) {
  49365. if (scene.getEngine().enableOfflineSupport) {
  49366. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  49367. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  49368. }
  49369. else {
  49370. manifestChecked(true);
  49371. }
  49372. }
  49373. else {
  49374. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  49375. }
  49376. };
  49377. // Public functions
  49378. SceneLoader.GetPluginForExtension = function (extension) {
  49379. return SceneLoader._getPluginForExtension(extension).plugin;
  49380. };
  49381. SceneLoader.RegisterPlugin = function (plugin) {
  49382. if (typeof plugin.extensions === "string") {
  49383. var extension = plugin.extensions;
  49384. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  49385. plugin: plugin,
  49386. isBinary: false
  49387. };
  49388. }
  49389. else {
  49390. var extensions = plugin.extensions;
  49391. Object.keys(extensions).forEach(function (extension) {
  49392. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  49393. plugin: plugin,
  49394. isBinary: extensions[extension].isBinary
  49395. };
  49396. });
  49397. }
  49398. };
  49399. /**
  49400. * Import meshes into a scene
  49401. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  49402. * @param rootUrl a string that defines the root url for scene and resources
  49403. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49404. * @param scene the instance of BABYLON.Scene to append to
  49405. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  49406. * @param onProgress a callback with a progress event for each file being loaded
  49407. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49408. */
  49409. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49410. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  49411. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  49412. return;
  49413. }
  49414. var loadingToken = {};
  49415. scene._addPendingData(loadingToken);
  49416. var errorHandler = function (message, exception) {
  49417. if (onError) {
  49418. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  49419. }
  49420. scene._removePendingData(loadingToken);
  49421. };
  49422. var progressHandler = function (event) {
  49423. if (onProgress) {
  49424. onProgress(event);
  49425. }
  49426. };
  49427. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  49428. if (plugin.importMesh) {
  49429. var syncedPlugin = plugin;
  49430. var meshes = [];
  49431. var particleSystems = [];
  49432. var skeletons = [];
  49433. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  49434. return;
  49435. }
  49436. if (onSuccess) {
  49437. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  49438. onSuccess(meshes, particleSystems, skeletons);
  49439. scene._removePendingData(loadingToken);
  49440. }
  49441. }
  49442. else {
  49443. var asyncedPlugin = plugin;
  49444. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  49445. if (onSuccess) {
  49446. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  49447. onSuccess(meshes, particleSystems, skeletons);
  49448. scene._removePendingData(loadingToken);
  49449. }
  49450. }, progressHandler, errorHandler);
  49451. }
  49452. }, progressHandler, errorHandler);
  49453. };
  49454. /**
  49455. * Load a scene
  49456. * @param rootUrl a string that defines the root url for scene and resources
  49457. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49458. * @param engine is the instance of BABYLON.Engine to use to create the scene
  49459. * @param onSuccess a callback with the scene when import succeeds
  49460. * @param onProgress a callback with a progress event for each file being loaded
  49461. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49462. */
  49463. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  49464. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  49465. };
  49466. /**
  49467. * Append a scene
  49468. * @param rootUrl a string that defines the root url for scene and resources
  49469. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49470. * @param scene is the instance of BABYLON.Scene to append to
  49471. * @param onSuccess a callback with the scene when import succeeds
  49472. * @param onProgress a callback with a progress event for each file being loaded
  49473. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49474. */
  49475. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49476. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  49477. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  49478. return;
  49479. }
  49480. if (SceneLoader.ShowLoadingScreen) {
  49481. scene.getEngine().displayLoadingUI();
  49482. }
  49483. var loadingToken = {};
  49484. scene._addPendingData(loadingToken);
  49485. var errorHandler = function (message, exception) {
  49486. if (onError) {
  49487. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  49488. }
  49489. scene._removePendingData(loadingToken);
  49490. scene.getEngine().hideLoadingUI();
  49491. };
  49492. var progressHandler = function (event) {
  49493. if (onProgress) {
  49494. onProgress(event);
  49495. }
  49496. };
  49497. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  49498. if (plugin.load) {
  49499. var syncedPlugin = plugin;
  49500. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  49501. return;
  49502. }
  49503. if (onSuccess) {
  49504. onSuccess(scene);
  49505. }
  49506. scene.loadingPluginName = plugin.name;
  49507. scene._removePendingData(loadingToken);
  49508. }
  49509. else {
  49510. var asyncedPlugin = plugin;
  49511. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  49512. if (onSuccess) {
  49513. onSuccess(scene);
  49514. }
  49515. scene.loadingPluginName = plugin.name;
  49516. scene._removePendingData(loadingToken);
  49517. }, progressHandler, errorHandler);
  49518. }
  49519. if (SceneLoader.ShowLoadingScreen) {
  49520. scene.executeWhenReady(function () {
  49521. scene.getEngine().hideLoadingUI();
  49522. });
  49523. }
  49524. }, progressHandler, errorHandler);
  49525. };
  49526. // Flags
  49527. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  49528. SceneLoader._ShowLoadingScreen = true;
  49529. SceneLoader._CleanBoneMatrixWeights = false;
  49530. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  49531. // Members
  49532. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  49533. SceneLoader._registeredPlugins = {};
  49534. return SceneLoader;
  49535. }());
  49536. BABYLON.SceneLoader = SceneLoader;
  49537. ;
  49538. })(BABYLON || (BABYLON = {}));
  49539. //# sourceMappingURL=babylon.sceneLoader.js.map
  49540. var BABYLON;
  49541. (function (BABYLON) {
  49542. var Internals;
  49543. (function (Internals) {
  49544. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  49545. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49546. var parsedMaterial = parsedData.materials[index];
  49547. if (parsedMaterial.id === id) {
  49548. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49549. }
  49550. }
  49551. return null;
  49552. };
  49553. var isDescendantOf = function (mesh, names, hierarchyIds) {
  49554. for (var i in names) {
  49555. if (mesh.name === names[i]) {
  49556. hierarchyIds.push(mesh.id);
  49557. return true;
  49558. }
  49559. }
  49560. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  49561. hierarchyIds.push(mesh.id);
  49562. return true;
  49563. }
  49564. return false;
  49565. };
  49566. var logOperation = function (operation, producer) {
  49567. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  49568. };
  49569. BABYLON.SceneLoader.RegisterPlugin({
  49570. name: "babylon.js",
  49571. extensions: ".babylon",
  49572. canDirectLoad: function (data) {
  49573. if (data.indexOf("babylon") !== -1) {
  49574. return true;
  49575. }
  49576. return false;
  49577. },
  49578. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  49579. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49580. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49581. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49582. // and avoid problems with multiple concurrent .babylon loads.
  49583. var log = "importMesh has failed JSON parse";
  49584. try {
  49585. var parsedData = JSON.parse(data);
  49586. log = "";
  49587. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49588. if (!meshesNames) {
  49589. meshesNames = null;
  49590. }
  49591. else if (!Array.isArray(meshesNames)) {
  49592. meshesNames = [meshesNames];
  49593. }
  49594. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49595. var loadedSkeletonsIds = [];
  49596. var loadedMaterialsIds = [];
  49597. var hierarchyIds = [];
  49598. var index;
  49599. var cache;
  49600. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49601. var parsedMesh = parsedData.meshes[index];
  49602. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  49603. if (meshesNames !== null) {
  49604. // Remove found mesh name from list.
  49605. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  49606. }
  49607. //Geometry?
  49608. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  49609. //does the file contain geometries?
  49610. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  49611. //find the correct geometry and add it to the scene
  49612. var found = false;
  49613. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  49614. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  49615. return;
  49616. }
  49617. else {
  49618. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  49619. if (parsedGeometryData.id === parsedMesh.geometryId) {
  49620. switch (geometryType) {
  49621. case "boxes":
  49622. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  49623. break;
  49624. case "spheres":
  49625. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  49626. break;
  49627. case "cylinders":
  49628. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  49629. break;
  49630. case "toruses":
  49631. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  49632. break;
  49633. case "grounds":
  49634. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  49635. break;
  49636. case "planes":
  49637. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  49638. break;
  49639. case "torusKnots":
  49640. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  49641. break;
  49642. case "vertexData":
  49643. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  49644. break;
  49645. }
  49646. found = true;
  49647. }
  49648. });
  49649. }
  49650. });
  49651. if (found === false) {
  49652. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  49653. }
  49654. }
  49655. }
  49656. // Material ?
  49657. if (parsedMesh.materialId) {
  49658. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  49659. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49660. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  49661. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  49662. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  49663. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  49664. var subMatId = parsedMultiMaterial.materials[matIndex];
  49665. loadedMaterialsIds.push(subMatId);
  49666. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  49667. log += "\n\tMaterial " + mat.toString(fullDetails);
  49668. }
  49669. loadedMaterialsIds.push(parsedMultiMaterial.id);
  49670. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49671. materialFound = true;
  49672. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  49673. break;
  49674. }
  49675. }
  49676. }
  49677. if (materialFound === false) {
  49678. loadedMaterialsIds.push(parsedMesh.materialId);
  49679. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  49680. if (!mat) {
  49681. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  49682. }
  49683. else {
  49684. log += "\n\tMaterial " + mat.toString(fullDetails);
  49685. }
  49686. }
  49687. }
  49688. // Skeleton ?
  49689. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49690. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  49691. if (skeletonAlreadyLoaded === false) {
  49692. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  49693. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  49694. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  49695. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49696. skeletons.push(skeleton);
  49697. loadedSkeletonsIds.push(parsedSkeleton.id);
  49698. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  49699. }
  49700. }
  49701. }
  49702. }
  49703. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49704. meshes.push(mesh);
  49705. log += "\n\tMesh " + mesh.toString(fullDetails);
  49706. }
  49707. }
  49708. // Connecting parents
  49709. var currentMesh;
  49710. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49711. currentMesh = scene.meshes[index];
  49712. if (currentMesh._waitingParentId) {
  49713. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  49714. currentMesh._waitingParentId = undefined;
  49715. }
  49716. }
  49717. // freeze and compute world matrix application
  49718. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49719. currentMesh = scene.meshes[index];
  49720. if (currentMesh._waitingFreezeWorldMatrix) {
  49721. currentMesh.freezeWorldMatrix();
  49722. currentMesh._waitingFreezeWorldMatrix = undefined;
  49723. }
  49724. else {
  49725. currentMesh.computeWorldMatrix(true);
  49726. }
  49727. }
  49728. }
  49729. // Particles
  49730. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49731. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49732. var parsedParticleSystem = parsedData.particleSystems[index];
  49733. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  49734. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  49735. }
  49736. }
  49737. }
  49738. return true;
  49739. }
  49740. catch (err) {
  49741. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  49742. log = null;
  49743. throw err;
  49744. }
  49745. finally {
  49746. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49747. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49748. }
  49749. }
  49750. },
  49751. load: function (scene, data, rootUrl) {
  49752. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49753. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49754. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49755. // and avoid problems with multiple concurrent .babylon loads.
  49756. var log = "importScene has failed JSON parse";
  49757. try {
  49758. var parsedData = JSON.parse(data);
  49759. log = "";
  49760. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49761. // Scene
  49762. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  49763. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  49764. }
  49765. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  49766. scene.autoClear = parsedData.autoClear;
  49767. }
  49768. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  49769. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  49770. }
  49771. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  49772. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  49773. }
  49774. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  49775. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  49776. }
  49777. // Fog
  49778. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  49779. scene.fogMode = parsedData.fogMode;
  49780. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  49781. scene.fogStart = parsedData.fogStart;
  49782. scene.fogEnd = parsedData.fogEnd;
  49783. scene.fogDensity = parsedData.fogDensity;
  49784. log += "\tFog mode for scene: ";
  49785. switch (scene.fogMode) {
  49786. // getters not compiling, so using hardcoded
  49787. case 1:
  49788. log += "exp\n";
  49789. break;
  49790. case 2:
  49791. log += "exp2\n";
  49792. break;
  49793. case 3:
  49794. log += "linear\n";
  49795. break;
  49796. }
  49797. }
  49798. //Physics
  49799. if (parsedData.physicsEnabled) {
  49800. var physicsPlugin;
  49801. if (parsedData.physicsEngine === "cannon") {
  49802. physicsPlugin = new BABYLON.CannonJSPlugin();
  49803. }
  49804. else if (parsedData.physicsEngine === "oimo") {
  49805. physicsPlugin = new BABYLON.OimoJSPlugin();
  49806. }
  49807. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  49808. //else - default engine, which is currently oimo
  49809. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  49810. scene.enablePhysics(physicsGravity, physicsPlugin);
  49811. }
  49812. // Metadata
  49813. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  49814. scene.metadata = parsedData.metadata;
  49815. }
  49816. //collisions, if defined. otherwise, default is true
  49817. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  49818. scene.collisionsEnabled = parsedData.collisionsEnabled;
  49819. }
  49820. scene.workerCollisions = !!parsedData.workerCollisions;
  49821. var index;
  49822. var cache;
  49823. // Lights
  49824. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  49825. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  49826. var parsedLight = parsedData.lights[index];
  49827. var light = BABYLON.Light.Parse(parsedLight, scene);
  49828. log += (index === 0 ? "\n\tLights:" : "");
  49829. log += "\n\t\t" + light.toString(fullDetails);
  49830. }
  49831. }
  49832. // Animations
  49833. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  49834. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  49835. var parsedAnimation = parsedData.animations[index];
  49836. var animation = BABYLON.Animation.Parse(parsedAnimation);
  49837. scene.animations.push(animation);
  49838. log += (index === 0 ? "\n\tAnimations:" : "");
  49839. log += "\n\t\t" + animation.toString(fullDetails);
  49840. }
  49841. }
  49842. if (parsedData.autoAnimate) {
  49843. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  49844. }
  49845. // Materials
  49846. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  49847. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49848. var parsedMaterial = parsedData.materials[index];
  49849. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49850. log += (index === 0 ? "\n\tMaterials:" : "");
  49851. log += "\n\t\t" + mat.toString(fullDetails);
  49852. }
  49853. }
  49854. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49855. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  49856. var parsedMultiMaterial = parsedData.multiMaterials[index];
  49857. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49858. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  49859. log += "\n\t\t" + mmat.toString(fullDetails);
  49860. }
  49861. }
  49862. // Morph targets
  49863. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  49864. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  49865. var managerData = _a[_i];
  49866. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  49867. }
  49868. }
  49869. // Skeletons
  49870. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49871. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  49872. var parsedSkeleton = parsedData.skeletons[index];
  49873. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49874. log += (index === 0 ? "\n\tSkeletons:" : "");
  49875. log += "\n\t\t" + skeleton.toString(fullDetails);
  49876. }
  49877. }
  49878. // Geometries
  49879. var geometries = parsedData.geometries;
  49880. if (geometries !== undefined && geometries !== null) {
  49881. // Boxes
  49882. var boxes = geometries.boxes;
  49883. if (boxes !== undefined && boxes !== null) {
  49884. for (index = 0, cache = boxes.length; index < cache; index++) {
  49885. var parsedBox = boxes[index];
  49886. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  49887. }
  49888. }
  49889. // Spheres
  49890. var spheres = geometries.spheres;
  49891. if (spheres !== undefined && spheres !== null) {
  49892. for (index = 0, cache = spheres.length; index < cache; index++) {
  49893. var parsedSphere = spheres[index];
  49894. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  49895. }
  49896. }
  49897. // Cylinders
  49898. var cylinders = geometries.cylinders;
  49899. if (cylinders !== undefined && cylinders !== null) {
  49900. for (index = 0, cache = cylinders.length; index < cache; index++) {
  49901. var parsedCylinder = cylinders[index];
  49902. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  49903. }
  49904. }
  49905. // Toruses
  49906. var toruses = geometries.toruses;
  49907. if (toruses !== undefined && toruses !== null) {
  49908. for (index = 0, cache = toruses.length; index < cache; index++) {
  49909. var parsedTorus = toruses[index];
  49910. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  49911. }
  49912. }
  49913. // Grounds
  49914. var grounds = geometries.grounds;
  49915. if (grounds !== undefined && grounds !== null) {
  49916. for (index = 0, cache = grounds.length; index < cache; index++) {
  49917. var parsedGround = grounds[index];
  49918. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  49919. }
  49920. }
  49921. // Planes
  49922. var planes = geometries.planes;
  49923. if (planes !== undefined && planes !== null) {
  49924. for (index = 0, cache = planes.length; index < cache; index++) {
  49925. var parsedPlane = planes[index];
  49926. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  49927. }
  49928. }
  49929. // TorusKnots
  49930. var torusKnots = geometries.torusKnots;
  49931. if (torusKnots !== undefined && torusKnots !== null) {
  49932. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  49933. var parsedTorusKnot = torusKnots[index];
  49934. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  49935. }
  49936. }
  49937. // VertexData
  49938. var vertexData = geometries.vertexData;
  49939. if (vertexData !== undefined && vertexData !== null) {
  49940. for (index = 0, cache = vertexData.length; index < cache; index++) {
  49941. var parsedVertexData = vertexData[index];
  49942. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  49943. }
  49944. }
  49945. }
  49946. // Meshes
  49947. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49948. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49949. var parsedMesh = parsedData.meshes[index];
  49950. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49951. log += (index === 0 ? "\n\tMeshes:" : "");
  49952. log += "\n\t\t" + mesh.toString(fullDetails);
  49953. }
  49954. }
  49955. // Cameras
  49956. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  49957. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  49958. var parsedCamera = parsedData.cameras[index];
  49959. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  49960. log += (index === 0 ? "\n\tCameras:" : "");
  49961. log += "\n\t\t" + camera.toString(fullDetails);
  49962. }
  49963. }
  49964. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  49965. scene.setActiveCameraByID(parsedData.activeCameraID);
  49966. }
  49967. // Browsing all the graph to connect the dots
  49968. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  49969. var camera = scene.cameras[index];
  49970. if (camera._waitingParentId) {
  49971. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  49972. camera._waitingParentId = undefined;
  49973. }
  49974. }
  49975. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49976. var light = scene.lights[index];
  49977. if (light._waitingParentId) {
  49978. light.parent = scene.getLastEntryByID(light._waitingParentId);
  49979. light._waitingParentId = undefined;
  49980. }
  49981. }
  49982. // Sounds
  49983. var loadedSounds = [];
  49984. var loadedSound;
  49985. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  49986. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  49987. var parsedSound = parsedData.sounds[index];
  49988. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49989. if (!parsedSound.url)
  49990. parsedSound.url = parsedSound.name;
  49991. if (!loadedSounds[parsedSound.url]) {
  49992. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  49993. loadedSounds[parsedSound.url] = loadedSound;
  49994. }
  49995. else {
  49996. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  49997. }
  49998. }
  49999. else {
  50000. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  50001. }
  50002. }
  50003. }
  50004. loadedSounds = [];
  50005. // Connect parents & children and parse actions
  50006. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  50007. var mesh = scene.meshes[index];
  50008. if (mesh._waitingParentId) {
  50009. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  50010. mesh._waitingParentId = undefined;
  50011. }
  50012. if (mesh._waitingActions) {
  50013. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  50014. mesh._waitingActions = undefined;
  50015. }
  50016. }
  50017. // freeze world matrix application
  50018. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  50019. var currentMesh = scene.meshes[index];
  50020. if (currentMesh._waitingFreezeWorldMatrix) {
  50021. currentMesh.freezeWorldMatrix();
  50022. currentMesh._waitingFreezeWorldMatrix = undefined;
  50023. }
  50024. else {
  50025. currentMesh.computeWorldMatrix(true);
  50026. }
  50027. }
  50028. // Particles Systems
  50029. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  50030. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  50031. var parsedParticleSystem = parsedData.particleSystems[index];
  50032. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  50033. }
  50034. }
  50035. // Lens flares
  50036. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  50037. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  50038. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  50039. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  50040. }
  50041. }
  50042. // Shadows
  50043. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  50044. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  50045. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  50046. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  50047. }
  50048. }
  50049. // Lights exclusions / inclusions
  50050. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  50051. var light = scene.lights[index];
  50052. // Excluded check
  50053. if (light._excludedMeshesIds.length > 0) {
  50054. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  50055. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  50056. if (excludedMesh) {
  50057. light.excludedMeshes.push(excludedMesh);
  50058. }
  50059. }
  50060. light._excludedMeshesIds = [];
  50061. }
  50062. // Included check
  50063. if (light._includedOnlyMeshesIds.length > 0) {
  50064. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  50065. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  50066. if (includedOnlyMesh) {
  50067. light.includedOnlyMeshes.push(includedOnlyMesh);
  50068. }
  50069. }
  50070. light._includedOnlyMeshesIds = [];
  50071. }
  50072. }
  50073. // Actions (scene)
  50074. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  50075. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  50076. }
  50077. // Finish
  50078. return true;
  50079. }
  50080. catch (err) {
  50081. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  50082. log = null;
  50083. throw err;
  50084. }
  50085. finally {
  50086. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  50087. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  50088. }
  50089. }
  50090. }
  50091. });
  50092. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50093. })(BABYLON || (BABYLON = {}));
  50094. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  50095. var BABYLON;
  50096. (function (BABYLON) {
  50097. var FilesInput = (function () {
  50098. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback) {
  50099. this._engine = engine;
  50100. this._currentScene = scene;
  50101. this._sceneLoadedCallback = sceneLoadedCallback;
  50102. this._progressCallback = progressCallback;
  50103. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  50104. this._textureLoadingCallback = textureLoadingCallback;
  50105. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  50106. this._onReloadCallback = onReloadCallback;
  50107. }
  50108. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  50109. var _this = this;
  50110. if (elementToMonitor) {
  50111. this._elementToMonitor = elementToMonitor;
  50112. this._dragEnterHandler = function (e) { _this.drag(e); };
  50113. this._dragOverHandler = function (e) { _this.drag(e); };
  50114. this._dropHandler = function (e) { _this.drop(e); };
  50115. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  50116. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  50117. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  50118. }
  50119. };
  50120. FilesInput.prototype.dispose = function () {
  50121. if (!this._elementToMonitor) {
  50122. return;
  50123. }
  50124. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  50125. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  50126. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  50127. };
  50128. FilesInput.prototype.renderFunction = function () {
  50129. if (this._additionalRenderLoopLogicCallback) {
  50130. this._additionalRenderLoopLogicCallback();
  50131. }
  50132. if (this._currentScene) {
  50133. if (this._textureLoadingCallback) {
  50134. var remaining = this._currentScene.getWaitingItemsCount();
  50135. if (remaining > 0) {
  50136. this._textureLoadingCallback(remaining);
  50137. }
  50138. }
  50139. this._currentScene.render();
  50140. }
  50141. };
  50142. FilesInput.prototype.drag = function (e) {
  50143. e.stopPropagation();
  50144. e.preventDefault();
  50145. };
  50146. FilesInput.prototype.drop = function (eventDrop) {
  50147. eventDrop.stopPropagation();
  50148. eventDrop.preventDefault();
  50149. this.loadFiles(eventDrop);
  50150. };
  50151. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  50152. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  50153. reader.readEntries(function (fileEntries) {
  50154. var remaining = fileEntries.length;
  50155. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  50156. var fileEntry = fileEntries_1[_i];
  50157. if (fileEntry.isFile) {
  50158. fileEntry.file(function (file) {
  50159. file.correctName = relativePath + file.name;
  50160. files.push(file);
  50161. remaining--;
  50162. if (remaining === 0) {
  50163. callback();
  50164. }
  50165. });
  50166. }
  50167. else {
  50168. remaining--;
  50169. if (remaining === 0) {
  50170. callback();
  50171. }
  50172. }
  50173. }
  50174. });
  50175. };
  50176. FilesInput.prototype._processFiles = function (files) {
  50177. for (var i = 0; i < files.length; i++) {
  50178. var name = files[i].correctName.toLowerCase();
  50179. var extension = name.split('.').pop();
  50180. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  50181. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  50182. this._sceneFileToLoad = files[i];
  50183. }
  50184. else {
  50185. FilesInput.FilesToLoad[name] = files[i];
  50186. }
  50187. }
  50188. if (this._onReloadCallback) {
  50189. this._onReloadCallback(this._sceneFileToLoad);
  50190. }
  50191. else {
  50192. this.reload();
  50193. }
  50194. };
  50195. FilesInput.prototype.loadFiles = function (event) {
  50196. var _this = this;
  50197. if (this._startingProcessingFilesCallback)
  50198. this._startingProcessingFilesCallback();
  50199. // Handling data transfer via drag'n'drop
  50200. if (event && event.dataTransfer && event.dataTransfer.files) {
  50201. this._filesToLoad = event.dataTransfer.files;
  50202. }
  50203. // Handling files from input files
  50204. if (event && event.target && event.target.files) {
  50205. this._filesToLoad = event.target.files;
  50206. }
  50207. if (this._filesToLoad && this._filesToLoad.length > 0) {
  50208. var files_1 = [];
  50209. var folders = [];
  50210. var items = event.dataTransfer ? event.dataTransfer.items : null;
  50211. for (var i = 0; i < this._filesToLoad.length; i++) {
  50212. var fileToLoad = this._filesToLoad[i];
  50213. var name_1 = fileToLoad.name.toLowerCase();
  50214. var type = fileToLoad.type;
  50215. var entry = void 0;
  50216. fileToLoad.correctName = name_1;
  50217. if (items) {
  50218. var item = items[i];
  50219. if (item.getAsEntry) {
  50220. entry = item.getAsEntry();
  50221. }
  50222. else if (item.webkitGetAsEntry) {
  50223. entry = item.webkitGetAsEntry();
  50224. }
  50225. }
  50226. if (!entry) {
  50227. files_1.push(fileToLoad);
  50228. }
  50229. else {
  50230. if (entry.isDirectory) {
  50231. folders.push(entry);
  50232. }
  50233. else {
  50234. files_1.push(fileToLoad);
  50235. }
  50236. }
  50237. }
  50238. if (folders.length === 0) {
  50239. this._processFiles(files_1);
  50240. }
  50241. else {
  50242. var remaining = folders.length;
  50243. // Extract folder content
  50244. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  50245. var folder = folders_1[_i];
  50246. this._handleFolderDrop(folder, files_1, function () {
  50247. remaining--;
  50248. if (remaining === 0) {
  50249. _this._processFiles(files_1);
  50250. }
  50251. });
  50252. }
  50253. }
  50254. }
  50255. };
  50256. FilesInput.prototype.reload = function () {
  50257. var _this = this;
  50258. // If a ".babylon" file has been provided
  50259. if (this._sceneFileToLoad) {
  50260. if (this._currentScene) {
  50261. if (BABYLON.Tools.errorsCount > 0) {
  50262. BABYLON.Tools.ClearLogCache();
  50263. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  50264. }
  50265. this._engine.stopRenderLoop();
  50266. this._currentScene.dispose();
  50267. }
  50268. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  50269. _this._currentScene = newScene;
  50270. if (_this._sceneLoadedCallback) {
  50271. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  50272. }
  50273. // Wait for textures and shaders to be ready
  50274. _this._currentScene.executeWhenReady(function () {
  50275. _this._engine.runRenderLoop(function () {
  50276. _this.renderFunction();
  50277. });
  50278. });
  50279. }, function (progress) {
  50280. if (_this._progressCallback) {
  50281. _this._progressCallback(progress);
  50282. }
  50283. });
  50284. }
  50285. else {
  50286. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  50287. }
  50288. };
  50289. FilesInput.FilesToLoad = new Array();
  50290. return FilesInput;
  50291. }());
  50292. BABYLON.FilesInput = FilesInput;
  50293. })(BABYLON || (BABYLON = {}));
  50294. //# sourceMappingURL=babylon.filesInput.js.map
  50295. var BABYLON;
  50296. (function (BABYLON) {
  50297. var FramingBehavior = (function () {
  50298. function FramingBehavior() {
  50299. this._mode = FramingBehavior.FitFrustumSidesMode;
  50300. this._radiusScale = 1.0;
  50301. this._positionScale = 0.5;
  50302. this._defaultElevation = 0.3;
  50303. this._elevationReturnTime = 1500;
  50304. this._elevationReturnWaitTime = 1000;
  50305. this._zoomStopsAnimation = false;
  50306. this._framingTime = 1500;
  50307. this._isPointerDown = false;
  50308. this._lastFrameTime = null;
  50309. this._lastInteractionTime = -Infinity;
  50310. // Framing control
  50311. this._animatables = new Array();
  50312. this._betaIsAnimating = false;
  50313. this._lastFrameRadius = 0;
  50314. }
  50315. Object.defineProperty(FramingBehavior.prototype, "name", {
  50316. get: function () {
  50317. return "Framing";
  50318. },
  50319. enumerable: true,
  50320. configurable: true
  50321. });
  50322. Object.defineProperty(FramingBehavior.prototype, "mode", {
  50323. /**
  50324. * Gets current mode used by the behavior.
  50325. */
  50326. get: function () {
  50327. return this._mode;
  50328. },
  50329. /**
  50330. * Sets the current mode used by the behavior
  50331. */
  50332. set: function (mode) {
  50333. this._mode = mode;
  50334. },
  50335. enumerable: true,
  50336. configurable: true
  50337. });
  50338. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  50339. /**
  50340. * Gets the scale applied to the radius
  50341. */
  50342. get: function () {
  50343. return this._radiusScale;
  50344. },
  50345. /**
  50346. * Sets the scale applied to the radius (1 by default)
  50347. */
  50348. set: function (radius) {
  50349. this._radiusScale = radius;
  50350. },
  50351. enumerable: true,
  50352. configurable: true
  50353. });
  50354. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  50355. /**
  50356. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  50357. */
  50358. get: function () {
  50359. return this._positionScale;
  50360. },
  50361. /**
  50362. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  50363. */
  50364. set: function (scale) {
  50365. this._positionScale = scale;
  50366. },
  50367. enumerable: true,
  50368. configurable: true
  50369. });
  50370. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  50371. /**
  50372. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  50373. * behaviour is triggered, in radians.
  50374. */
  50375. get: function () {
  50376. return this._defaultElevation;
  50377. },
  50378. /**
  50379. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  50380. * behaviour is triggered, in radians.
  50381. */
  50382. set: function (elevation) {
  50383. this._defaultElevation = elevation;
  50384. },
  50385. enumerable: true,
  50386. configurable: true
  50387. });
  50388. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  50389. /**
  50390. * Gets the time (in milliseconds) taken to return to the default beta position.
  50391. * Negative value indicates camera should not return to default.
  50392. */
  50393. get: function () {
  50394. return this._elevationReturnTime;
  50395. },
  50396. /**
  50397. * Sets the time (in milliseconds) taken to return to the default beta position.
  50398. * Negative value indicates camera should not return to default.
  50399. */
  50400. set: function (speed) {
  50401. this._elevationReturnTime = speed;
  50402. },
  50403. enumerable: true,
  50404. configurable: true
  50405. });
  50406. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  50407. /**
  50408. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  50409. */
  50410. get: function () {
  50411. return this._elevationReturnWaitTime;
  50412. },
  50413. /**
  50414. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  50415. */
  50416. set: function (time) {
  50417. this._elevationReturnWaitTime = time;
  50418. },
  50419. enumerable: true,
  50420. configurable: true
  50421. });
  50422. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  50423. /**
  50424. * Gets the flag that indicates if user zooming should stop animation.
  50425. */
  50426. get: function () {
  50427. return this._zoomStopsAnimation;
  50428. },
  50429. /**
  50430. * Sets the flag that indicates if user zooming should stop animation.
  50431. */
  50432. set: function (flag) {
  50433. this._zoomStopsAnimation = flag;
  50434. },
  50435. enumerable: true,
  50436. configurable: true
  50437. });
  50438. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  50439. /**
  50440. * Gets the transition time when framing the mesh, in milliseconds
  50441. */
  50442. get: function () {
  50443. return this._framingTime;
  50444. },
  50445. /**
  50446. * Sets the transition time when framing the mesh, in milliseconds
  50447. */
  50448. set: function (time) {
  50449. this._framingTime = time;
  50450. },
  50451. enumerable: true,
  50452. configurable: true
  50453. });
  50454. FramingBehavior.prototype.attach = function (camera) {
  50455. var _this = this;
  50456. this._attachedCamera = camera;
  50457. var scene = this._attachedCamera.getScene();
  50458. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  50459. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  50460. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50461. _this._isPointerDown = true;
  50462. return;
  50463. }
  50464. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  50465. _this._isPointerDown = false;
  50466. }
  50467. });
  50468. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  50469. if (mesh) {
  50470. _this.zoomOnMesh(mesh);
  50471. }
  50472. });
  50473. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50474. // Stop the animation if there is user interaction and the animation should stop for this interaction
  50475. _this._applyUserInteraction();
  50476. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  50477. // back to the default position after a given timeout
  50478. _this._maintainCameraAboveGround();
  50479. });
  50480. };
  50481. FramingBehavior.prototype.detach = function () {
  50482. var scene = this._attachedCamera.getScene();
  50483. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  50484. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50485. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50486. this._attachedCamera = null;
  50487. };
  50488. /**
  50489. * Targets the given mesh and updates zoom level accordingly.
  50490. * @param mesh The mesh to target.
  50491. * @param radius Optional. If a cached radius position already exists, overrides default.
  50492. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  50493. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  50494. */
  50495. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ) {
  50496. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  50497. mesh.computeWorldMatrix(true);
  50498. var boundingBox = mesh.getBoundingInfo().boundingBox;
  50499. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ);
  50500. };
  50501. /**
  50502. * Targets the given mesh and updates zoom level accordingly.
  50503. * @param mesh The mesh to target.
  50504. * @param radius Optional. If a cached radius position already exists, overrides default.
  50505. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  50506. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  50507. */
  50508. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ) {
  50509. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  50510. var zoomTarget;
  50511. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  50512. var bottom = minimumWorld.y;
  50513. var top = maximumWorld.y;
  50514. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  50515. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  50516. if (focusOnOriginXZ) {
  50517. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  50518. }
  50519. else {
  50520. var centerWorld = minimumWorld.add(radiusWorld);
  50521. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  50522. }
  50523. if (!this._vectorTransition) {
  50524. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  50525. }
  50526. this._betaIsAnimating = true;
  50527. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  50528. // sets the radius and lower radius bounds
  50529. // Small delta ensures camera is not always at lower zoom limit.
  50530. var delta = 0.1;
  50531. var radius = 0;
  50532. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  50533. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  50534. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  50535. radius = position;
  50536. }
  50537. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  50538. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  50539. if (this._attachedCamera.lowerRadiusLimit === null) {
  50540. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  50541. }
  50542. }
  50543. // transition to new radius
  50544. if (!this._radiusTransition) {
  50545. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  50546. }
  50547. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime));
  50548. };
  50549. /**
  50550. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  50551. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  50552. * frustum width.
  50553. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  50554. * to fully enclose the mesh in the viewing frustum.
  50555. */
  50556. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  50557. var size = maximumWorld.subtract(minimumWorld);
  50558. var boxVectorGlobalDiagonal = size.length();
  50559. var frustumSlope = this._getFrustumSlope();
  50560. // Formula for setting distance
  50561. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  50562. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  50563. // Horizon distance
  50564. var radius = radiusWithoutFraming * this._radiusScale;
  50565. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  50566. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  50567. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  50568. var camera = this._attachedCamera;
  50569. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  50570. // Don't exceed the requested limit
  50571. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  50572. }
  50573. // Don't exceed the upper radius limit
  50574. if (camera.upperRadiusLimit) {
  50575. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  50576. }
  50577. return distance;
  50578. };
  50579. /**
  50580. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  50581. * is automatically returned to its default position (expected to be above ground plane).
  50582. */
  50583. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  50584. var _this = this;
  50585. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  50586. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  50587. var limitBeta = Math.PI * 0.5;
  50588. // Bring the camera back up if below the ground plane
  50589. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  50590. this._betaIsAnimating = true;
  50591. //Transition to new position
  50592. this.stopAllAnimations();
  50593. if (!this._betaTransition) {
  50594. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  50595. }
  50596. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  50597. _this._clearAnimationLocks();
  50598. _this.stopAllAnimations();
  50599. }));
  50600. }
  50601. };
  50602. /**
  50603. * Returns the frustum slope based on the canvas ratio and camera FOV
  50604. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  50605. */
  50606. FramingBehavior.prototype._getFrustumSlope = function () {
  50607. // Calculate the viewport ratio
  50608. // Aspect Ratio is Height/Width.
  50609. var camera = this._attachedCamera;
  50610. var engine = camera.getScene().getEngine();
  50611. var aspectRatio = engine.getAspectRatio(camera);
  50612. // Camera FOV is the vertical field of view (top-bottom) in radians.
  50613. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  50614. var frustumSlopeY = Math.tan(camera.fov / 2);
  50615. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  50616. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  50617. // along the forward vector.
  50618. var frustumSlopeX = frustumSlopeY * aspectRatio;
  50619. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  50620. };
  50621. /**
  50622. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  50623. */
  50624. FramingBehavior.prototype._clearAnimationLocks = function () {
  50625. this._betaIsAnimating = false;
  50626. };
  50627. /**
  50628. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  50629. */
  50630. FramingBehavior.prototype._applyUserInteraction = function () {
  50631. if (this.isUserIsMoving) {
  50632. this._lastInteractionTime = BABYLON.Tools.Now;
  50633. this.stopAllAnimations();
  50634. this._clearAnimationLocks();
  50635. }
  50636. };
  50637. /**
  50638. * Stops and removes all animations that have been applied to the camera
  50639. */
  50640. FramingBehavior.prototype.stopAllAnimations = function () {
  50641. this._attachedCamera.animations = [];
  50642. while (this._animatables.length) {
  50643. if (this._animatables[0]) {
  50644. this._animatables[0].onAnimationEnd = null;
  50645. this._animatables[0].stop();
  50646. }
  50647. this._animatables.shift();
  50648. }
  50649. };
  50650. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  50651. /**
  50652. * Gets a value indicating if the user is moving the camera
  50653. */
  50654. get: function () {
  50655. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  50656. this._attachedCamera.inertialBetaOffset !== 0 ||
  50657. this._attachedCamera.inertialRadiusOffset !== 0 ||
  50658. this._attachedCamera.inertialPanningX !== 0 ||
  50659. this._attachedCamera.inertialPanningY !== 0 ||
  50660. this._isPointerDown;
  50661. },
  50662. enumerable: true,
  50663. configurable: true
  50664. });
  50665. /**
  50666. * The easing function used by animations
  50667. */
  50668. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  50669. /**
  50670. * The easing mode used by animations
  50671. */
  50672. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  50673. // Statics
  50674. /**
  50675. * The camera can move all the way towards the mesh.
  50676. */
  50677. FramingBehavior.IgnoreBoundsSizeMode = 0;
  50678. /**
  50679. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  50680. */
  50681. FramingBehavior.FitFrustumSidesMode = 1;
  50682. return FramingBehavior;
  50683. }());
  50684. BABYLON.FramingBehavior = FramingBehavior;
  50685. })(BABYLON || (BABYLON = {}));
  50686. //# sourceMappingURL=babylon.framingBehavior.js.map
  50687. var BABYLON;
  50688. (function (BABYLON) {
  50689. /**
  50690. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  50691. */
  50692. var BouncingBehavior = (function () {
  50693. function BouncingBehavior() {
  50694. /**
  50695. * The duration of the animation, in milliseconds
  50696. */
  50697. this.transitionDuration = 450;
  50698. /**
  50699. * Length of the distance animated by the transition when lower radius is reached
  50700. */
  50701. this.lowerRadiusTransitionRange = 2;
  50702. /**
  50703. * Length of the distance animated by the transition when upper radius is reached
  50704. */
  50705. this.upperRadiusTransitionRange = -2;
  50706. this._autoTransitionRange = false;
  50707. // Animations
  50708. this._radiusIsAnimating = false;
  50709. this._radiusBounceTransition = null;
  50710. this._animatables = new Array();
  50711. }
  50712. Object.defineProperty(BouncingBehavior.prototype, "name", {
  50713. get: function () {
  50714. return "Bouncing";
  50715. },
  50716. enumerable: true,
  50717. configurable: true
  50718. });
  50719. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  50720. /**
  50721. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  50722. */
  50723. get: function () {
  50724. return this._autoTransitionRange;
  50725. },
  50726. /**
  50727. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  50728. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  50729. */
  50730. set: function (value) {
  50731. var _this = this;
  50732. if (this._autoTransitionRange === value) {
  50733. return;
  50734. }
  50735. this._autoTransitionRange = value;
  50736. var camera = this._attachedCamera;
  50737. if (value) {
  50738. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  50739. if (!mesh) {
  50740. return;
  50741. }
  50742. mesh.computeWorldMatrix(true);
  50743. var diagonal = mesh.getBoundingInfo().diagonalLength;
  50744. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  50745. _this.upperRadiusTransitionRange = diagonal * 0.05;
  50746. });
  50747. }
  50748. else if (this._onMeshTargetChangedObserver) {
  50749. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50750. }
  50751. },
  50752. enumerable: true,
  50753. configurable: true
  50754. });
  50755. BouncingBehavior.prototype.attach = function (camera) {
  50756. var _this = this;
  50757. this._attachedCamera = camera;
  50758. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50759. // Add the bounce animation to the lower radius limit
  50760. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  50761. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  50762. }
  50763. // Add the bounce animation to the upper radius limit
  50764. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  50765. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  50766. }
  50767. });
  50768. };
  50769. BouncingBehavior.prototype.detach = function () {
  50770. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50771. if (this._onMeshTargetChangedObserver) {
  50772. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50773. }
  50774. this._attachedCamera = null;
  50775. };
  50776. /**
  50777. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  50778. * @param radiusLimit The limit to check against.
  50779. * @return Bool to indicate if at limit.
  50780. */
  50781. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  50782. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  50783. return true;
  50784. }
  50785. return false;
  50786. };
  50787. /**
  50788. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  50789. * @param radiusDelta The delta by which to animate to. Can be negative.
  50790. */
  50791. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  50792. var _this = this;
  50793. if (!this._radiusBounceTransition) {
  50794. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  50795. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  50796. }
  50797. // Prevent zoom until bounce has completed
  50798. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  50799. this._attachedCamera.wheelPrecision = Infinity;
  50800. this._attachedCamera.inertialRadiusOffset = 0;
  50801. // Animate to the radius limit
  50802. this.stopAllAnimations();
  50803. this._radiusIsAnimating = true;
  50804. this._animatables.push(BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); }));
  50805. };
  50806. /**
  50807. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  50808. */
  50809. BouncingBehavior.prototype._clearAnimationLocks = function () {
  50810. this._radiusIsAnimating = false;
  50811. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  50812. };
  50813. /**
  50814. * Stops and removes all animations that have been applied to the camera
  50815. */
  50816. BouncingBehavior.prototype.stopAllAnimations = function () {
  50817. this._attachedCamera.animations = [];
  50818. while (this._animatables.length) {
  50819. this._animatables[0].onAnimationEnd = null;
  50820. this._animatables[0].stop();
  50821. this._animatables.shift();
  50822. }
  50823. };
  50824. /**
  50825. * The easing function used by animations
  50826. */
  50827. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  50828. /**
  50829. * The easing mode used by animations
  50830. */
  50831. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  50832. return BouncingBehavior;
  50833. }());
  50834. BABYLON.BouncingBehavior = BouncingBehavior;
  50835. })(BABYLON || (BABYLON = {}));
  50836. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  50837. var BABYLON;
  50838. (function (BABYLON) {
  50839. var AutoRotationBehavior = (function () {
  50840. function AutoRotationBehavior() {
  50841. this._zoomStopsAnimation = false;
  50842. this._idleRotationSpeed = 0.05;
  50843. this._idleRotationWaitTime = 2000;
  50844. this._idleRotationSpinupTime = 2000;
  50845. this._isPointerDown = false;
  50846. this._lastFrameTime = null;
  50847. this._lastInteractionTime = -Infinity;
  50848. this._cameraRotationSpeed = 0;
  50849. this._lastFrameRadius = 0;
  50850. }
  50851. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  50852. get: function () {
  50853. return "AutoRotation";
  50854. },
  50855. enumerable: true,
  50856. configurable: true
  50857. });
  50858. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  50859. /**
  50860. * Gets the flag that indicates if user zooming should stop animation.
  50861. */
  50862. get: function () {
  50863. return this._zoomStopsAnimation;
  50864. },
  50865. /**
  50866. * Sets the flag that indicates if user zooming should stop animation.
  50867. */
  50868. set: function (flag) {
  50869. this._zoomStopsAnimation = flag;
  50870. },
  50871. enumerable: true,
  50872. configurable: true
  50873. });
  50874. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  50875. /**
  50876. * Gets the default speed at which the camera rotates around the model.
  50877. */
  50878. get: function () {
  50879. return this._idleRotationSpeed;
  50880. },
  50881. /**
  50882. * Sets the default speed at which the camera rotates around the model.
  50883. */
  50884. set: function (speed) {
  50885. this._idleRotationSpeed = speed;
  50886. },
  50887. enumerable: true,
  50888. configurable: true
  50889. });
  50890. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  50891. /**
  50892. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  50893. */
  50894. get: function () {
  50895. return this._idleRotationWaitTime;
  50896. },
  50897. /**
  50898. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  50899. */
  50900. set: function (time) {
  50901. this._idleRotationWaitTime = time;
  50902. },
  50903. enumerable: true,
  50904. configurable: true
  50905. });
  50906. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  50907. /**
  50908. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  50909. */
  50910. get: function () {
  50911. return this._idleRotationSpinupTime;
  50912. },
  50913. /**
  50914. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  50915. */
  50916. set: function (time) {
  50917. this._idleRotationSpinupTime = time;
  50918. },
  50919. enumerable: true,
  50920. configurable: true
  50921. });
  50922. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  50923. /**
  50924. * Gets a value indicating if the camera is currently rotating because of this behavior
  50925. */
  50926. get: function () {
  50927. return Math.abs(this._cameraRotationSpeed) > 0;
  50928. },
  50929. enumerable: true,
  50930. configurable: true
  50931. });
  50932. AutoRotationBehavior.prototype.attach = function (camera) {
  50933. var _this = this;
  50934. this._attachedCamera = camera;
  50935. var scene = this._attachedCamera.getScene();
  50936. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  50937. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50938. _this._isPointerDown = true;
  50939. return;
  50940. }
  50941. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  50942. _this._isPointerDown = false;
  50943. }
  50944. });
  50945. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50946. var now = BABYLON.Tools.Now;
  50947. var dt = 0;
  50948. if (_this._lastFrameTime != null) {
  50949. dt = now - _this._lastFrameTime;
  50950. }
  50951. _this._lastFrameTime = now;
  50952. // Stop the animation if there is user interaction and the animation should stop for this interaction
  50953. _this._applyUserInteraction();
  50954. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  50955. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  50956. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  50957. // Step camera rotation by rotation speed
  50958. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  50959. });
  50960. };
  50961. AutoRotationBehavior.prototype.detach = function () {
  50962. var scene = this._attachedCamera.getScene();
  50963. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  50964. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50965. this._attachedCamera = null;
  50966. };
  50967. /**
  50968. * Returns true if user is scrolling.
  50969. * @return true if user is scrolling.
  50970. */
  50971. AutoRotationBehavior.prototype._userIsZooming = function () {
  50972. return this._attachedCamera.inertialRadiusOffset !== 0;
  50973. };
  50974. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  50975. var zoomHasHitLimit = false;
  50976. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  50977. zoomHasHitLimit = true;
  50978. }
  50979. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  50980. this._lastFrameRadius = this._attachedCamera.radius;
  50981. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  50982. };
  50983. /**
  50984. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  50985. */
  50986. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  50987. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  50988. this._lastInteractionTime = BABYLON.Tools.Now;
  50989. }
  50990. };
  50991. // Tools
  50992. AutoRotationBehavior.prototype._userIsMoving = function () {
  50993. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  50994. this._attachedCamera.inertialBetaOffset !== 0 ||
  50995. this._attachedCamera.inertialRadiusOffset !== 0 ||
  50996. this._attachedCamera.inertialPanningX !== 0 ||
  50997. this._attachedCamera.inertialPanningY !== 0 ||
  50998. this._isPointerDown;
  50999. };
  51000. return AutoRotationBehavior;
  51001. }());
  51002. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  51003. })(BABYLON || (BABYLON = {}));
  51004. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  51005. var BABYLON;
  51006. (function (BABYLON) {
  51007. var MorphTarget = (function () {
  51008. function MorphTarget(name, influence) {
  51009. if (influence === void 0) { influence = 0; }
  51010. this.name = name;
  51011. this.animations = new Array();
  51012. this.onInfluenceChanged = new BABYLON.Observable();
  51013. this.influence = influence;
  51014. }
  51015. Object.defineProperty(MorphTarget.prototype, "influence", {
  51016. get: function () {
  51017. return this._influence;
  51018. },
  51019. set: function (influence) {
  51020. if (this._influence === influence) {
  51021. return;
  51022. }
  51023. var previous = this._influence;
  51024. this._influence = influence;
  51025. if (this.onInfluenceChanged.hasObservers) {
  51026. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  51027. }
  51028. },
  51029. enumerable: true,
  51030. configurable: true
  51031. });
  51032. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  51033. get: function () {
  51034. return this._normals !== undefined;
  51035. },
  51036. enumerable: true,
  51037. configurable: true
  51038. });
  51039. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  51040. get: function () {
  51041. return this._tangents !== undefined;
  51042. },
  51043. enumerable: true,
  51044. configurable: true
  51045. });
  51046. MorphTarget.prototype.setPositions = function (data) {
  51047. this._positions = new Float32Array(data);
  51048. };
  51049. MorphTarget.prototype.getPositions = function () {
  51050. return this._positions;
  51051. };
  51052. MorphTarget.prototype.setNormals = function (data) {
  51053. this._normals = new Float32Array(data);
  51054. };
  51055. MorphTarget.prototype.getNormals = function () {
  51056. return this._normals;
  51057. };
  51058. MorphTarget.prototype.setTangents = function (data) {
  51059. this._tangents = new Float32Array(data);
  51060. };
  51061. MorphTarget.prototype.getTangents = function () {
  51062. return this._tangents;
  51063. };
  51064. /**
  51065. * Serializes the current target into a Serialization object.
  51066. * Returns the serialized object.
  51067. */
  51068. MorphTarget.prototype.serialize = function () {
  51069. var serializationObject = {};
  51070. serializationObject.name = this.name;
  51071. serializationObject.influence = this.influence;
  51072. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  51073. if (this.hasNormals) {
  51074. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  51075. }
  51076. if (this.hasTangents) {
  51077. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  51078. }
  51079. return serializationObject;
  51080. };
  51081. // Statics
  51082. MorphTarget.Parse = function (serializationObject) {
  51083. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  51084. result.setPositions(serializationObject.positions);
  51085. if (serializationObject.normals) {
  51086. result.setNormals(serializationObject.normals);
  51087. }
  51088. if (serializationObject.tangents) {
  51089. result.setTangents(serializationObject.tangents);
  51090. }
  51091. return result;
  51092. };
  51093. MorphTarget.FromMesh = function (mesh, name, influence) {
  51094. if (!name) {
  51095. name = mesh.name;
  51096. }
  51097. var result = new MorphTarget(name, influence);
  51098. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  51099. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  51100. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  51101. }
  51102. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  51103. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  51104. }
  51105. return result;
  51106. };
  51107. return MorphTarget;
  51108. }());
  51109. BABYLON.MorphTarget = MorphTarget;
  51110. })(BABYLON || (BABYLON = {}));
  51111. //# sourceMappingURL=babylon.morphTarget.js.map
  51112. var BABYLON;
  51113. (function (BABYLON) {
  51114. var MorphTargetManager = (function () {
  51115. function MorphTargetManager(scene) {
  51116. this._targets = new Array();
  51117. this._targetObservable = new Array();
  51118. this._activeTargets = new BABYLON.SmartArray(16);
  51119. this._supportsNormals = false;
  51120. this._supportsTangents = false;
  51121. this._vertexCount = 0;
  51122. this._uniqueId = 0;
  51123. this._tempInfluences = new Array();
  51124. if (!scene) {
  51125. scene = BABYLON.Engine.LastCreatedScene;
  51126. }
  51127. this._scene = scene;
  51128. this._scene.morphTargetManagers.push(this);
  51129. this._uniqueId = scene.getUniqueId();
  51130. }
  51131. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  51132. get: function () {
  51133. return this._uniqueId;
  51134. },
  51135. enumerable: true,
  51136. configurable: true
  51137. });
  51138. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  51139. get: function () {
  51140. return this._vertexCount;
  51141. },
  51142. enumerable: true,
  51143. configurable: true
  51144. });
  51145. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  51146. get: function () {
  51147. return this._supportsNormals;
  51148. },
  51149. enumerable: true,
  51150. configurable: true
  51151. });
  51152. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  51153. get: function () {
  51154. return this._supportsTangents;
  51155. },
  51156. enumerable: true,
  51157. configurable: true
  51158. });
  51159. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  51160. get: function () {
  51161. return this._targets.length;
  51162. },
  51163. enumerable: true,
  51164. configurable: true
  51165. });
  51166. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  51167. get: function () {
  51168. return this._activeTargets.length;
  51169. },
  51170. enumerable: true,
  51171. configurable: true
  51172. });
  51173. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  51174. get: function () {
  51175. return this._influences;
  51176. },
  51177. enumerable: true,
  51178. configurable: true
  51179. });
  51180. MorphTargetManager.prototype.getActiveTarget = function (index) {
  51181. return this._activeTargets.data[index];
  51182. };
  51183. MorphTargetManager.prototype.getTarget = function (index) {
  51184. return this._targets[index];
  51185. };
  51186. MorphTargetManager.prototype.addTarget = function (target) {
  51187. var _this = this;
  51188. if (this._vertexCount) {
  51189. if (this._vertexCount !== target.getPositions().length / 3) {
  51190. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  51191. return;
  51192. }
  51193. }
  51194. this._targets.push(target);
  51195. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  51196. _this._syncActiveTargets(needUpdate);
  51197. }));
  51198. this._syncActiveTargets(true);
  51199. };
  51200. MorphTargetManager.prototype.removeTarget = function (target) {
  51201. var index = this._targets.indexOf(target);
  51202. if (index >= 0) {
  51203. this._targets.splice(index, 1);
  51204. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  51205. this._vertexCount = 0;
  51206. this._syncActiveTargets(true);
  51207. }
  51208. };
  51209. /**
  51210. * Serializes the current manager into a Serialization object.
  51211. * Returns the serialized object.
  51212. */
  51213. MorphTargetManager.prototype.serialize = function () {
  51214. var serializationObject = {};
  51215. serializationObject.id = this.uniqueId;
  51216. serializationObject.targets = [];
  51217. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  51218. var target = _a[_i];
  51219. serializationObject.targets.push(target.serialize());
  51220. }
  51221. return serializationObject;
  51222. };
  51223. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  51224. this._syncActiveTargets(needUpdate);
  51225. };
  51226. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  51227. var influenceCount = 0;
  51228. this._activeTargets.reset();
  51229. this._supportsNormals = true;
  51230. this._supportsTangents = true;
  51231. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  51232. var target = _a[_i];
  51233. if (target.influence > 0) {
  51234. this._activeTargets.push(target);
  51235. this._tempInfluences[influenceCount++] = target.influence;
  51236. this._supportsNormals = this._supportsNormals && target.hasNormals;
  51237. this._supportsTangents = this._supportsTangents && target.hasTangents;
  51238. if (this._vertexCount === 0) {
  51239. this._vertexCount = target.getPositions().length / 3;
  51240. }
  51241. }
  51242. }
  51243. if (!this._influences || this._influences.length !== influenceCount) {
  51244. this._influences = new Float32Array(influenceCount);
  51245. }
  51246. for (var index = 0; index < influenceCount; index++) {
  51247. this._influences[index] = this._tempInfluences[index];
  51248. }
  51249. if (needUpdate) {
  51250. // Flag meshes as dirty to resync with the active targets
  51251. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  51252. var mesh = _c[_b];
  51253. if (mesh.morphTargetManager === this) {
  51254. mesh._syncGeometryWithMorphTargetManager();
  51255. }
  51256. }
  51257. }
  51258. };
  51259. // Statics
  51260. MorphTargetManager.Parse = function (serializationObject, scene) {
  51261. var result = new MorphTargetManager(scene);
  51262. result._uniqueId = serializationObject.id;
  51263. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  51264. var targetData = _a[_i];
  51265. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  51266. }
  51267. return result;
  51268. };
  51269. return MorphTargetManager;
  51270. }());
  51271. BABYLON.MorphTargetManager = MorphTargetManager;
  51272. })(BABYLON || (BABYLON = {}));
  51273. //# sourceMappingURL=babylon.morphTargetManager.js.map
  51274. 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 MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\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#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\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 MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \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#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \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#if defined(OPACITY) && OPACITYDIRECTUV == 0 \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#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \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#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \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) && REFLECTIVITYDIRECTUV == 0 \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#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \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#if defined(BUMP) && BUMPDIRECTUV == 0 \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) || defined(FORCENORMALFORWARD)\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 vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\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.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nfloat comp=sign(dot(normalW,faceNormal));\nnormalW*=-comp;\n#endif\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 REFLECTIVITY\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#if defined(ALPHATEST) || defined(ALPHABLEND)\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(viewDirectionW,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#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\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#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && !defined(USESPHERICALINFRAGMENT)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\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 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#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\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\nenvironmentRefraction*=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=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\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#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,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\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\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*=finalColor.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\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 MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\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 MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\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#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\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#if defined(OPACITY) && OPACITYDIRECTUV == 0\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#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\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#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\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) && SPECULARDIRECTUV == 0\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#if defined(BUMP) && BUMPDIRECTUV == 0\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#if defined(BUMP) || !defined(NORMAL)\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#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\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)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\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=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\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}"};
  51275. 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 vec4 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\nvec4 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#ifdef REFLECTIVITY \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\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\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;\nuniform vec4 vNormalReoderParams;\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 REFLECTIVITY\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;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\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 vec4 vNormalReoderParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\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.xyz);\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.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\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,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\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 computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\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 computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\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);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\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.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\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 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}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\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_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\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 cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\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>=cosHalfAngle)\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}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\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\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\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;\nmap.x=vNormalReoderParams.x+vNormalReoderParams.y*map.x;\nmap.y=vNormalReoderParams.z+vNormalReoderParams.w*map.y;\nmap=map*255./127.-128./127.;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\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\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,light{X}.shadowsInfo.w);\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,light{X}.shadowsInfo.w);\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,light{X}.shadowsInfo.w);\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,light{X}.shadowsInfo.w);\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;\nuniform vec4 vNormalReoderParams;\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; \nvec4 vNormalReoderParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  51276. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  51277. var BABYLON;
  51278. (function (BABYLON) {
  51279. var GridMaterialDefines = (function (_super) {
  51280. __extends(GridMaterialDefines, _super);
  51281. function GridMaterialDefines() {
  51282. var _this = _super.call(this) || this;
  51283. _this.TRANSPARENT = false;
  51284. _this.FOG = false;
  51285. _this.PREMULTIPLYALPHA = false;
  51286. _this.rebuild();
  51287. return _this;
  51288. }
  51289. return GridMaterialDefines;
  51290. }(BABYLON.MaterialDefines));
  51291. /**
  51292. * The grid materials allows you to wrap any shape with a grid.
  51293. * Colors are customizable.
  51294. */
  51295. var GridMaterial = (function (_super) {
  51296. __extends(GridMaterial, _super);
  51297. /**
  51298. * constructor
  51299. * @param name The name given to the material in order to identify it afterwards.
  51300. * @param scene The scene the material is used in.
  51301. */
  51302. function GridMaterial(name, scene) {
  51303. var _this = _super.call(this, name, scene) || this;
  51304. /**
  51305. * Main color of the grid (e.g. between lines)
  51306. */
  51307. _this.mainColor = BABYLON.Color3.Black();
  51308. /**
  51309. * Color of the grid lines.
  51310. */
  51311. _this.lineColor = BABYLON.Color3.Teal();
  51312. /**
  51313. * The scale of the grid compared to unit.
  51314. */
  51315. _this.gridRatio = 1.0;
  51316. /**
  51317. * The frequency of thicker lines.
  51318. */
  51319. _this.majorUnitFrequency = 10;
  51320. /**
  51321. * The visibility of minor units in the grid.
  51322. */
  51323. _this.minorUnitVisibility = 0.33;
  51324. /**
  51325. * The grid opacity outside of the lines.
  51326. */
  51327. _this.opacity = 1.0;
  51328. /**
  51329. * Determine RBG output is premultiplied by alpha value.
  51330. */
  51331. _this.preMultiplyAlpha = false;
  51332. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  51333. return _this;
  51334. }
  51335. /**
  51336. * Returns wehter or not the grid requires alpha blending.
  51337. */
  51338. GridMaterial.prototype.needAlphaBlending = function () {
  51339. return this.opacity < 1.0;
  51340. };
  51341. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  51342. if (this.isFrozen) {
  51343. if (this._wasPreviouslyReady && subMesh.effect) {
  51344. return true;
  51345. }
  51346. }
  51347. if (!subMesh._materialDefines) {
  51348. subMesh._materialDefines = new GridMaterialDefines();
  51349. }
  51350. var defines = subMesh._materialDefines;
  51351. var scene = this.getScene();
  51352. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  51353. if (this._renderId === scene.getRenderId()) {
  51354. return true;
  51355. }
  51356. }
  51357. var engine = scene.getEngine();
  51358. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  51359. defines.TRANSPARENT = !defines.TRANSPARENT;
  51360. defines.markAsUnprocessed();
  51361. }
  51362. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  51363. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  51364. defines.markAsUnprocessed();
  51365. }
  51366. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  51367. // Get correct effect
  51368. if (defines.isDirty) {
  51369. defines.markAsProcessed();
  51370. scene.resetCachedMaterial();
  51371. // Attributes
  51372. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  51373. // Defines
  51374. var join = defines.toString();
  51375. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "vFogInfos", "vFogColor", "world", "view"], [], join, null, this.onCompiled, this.onError), defines);
  51376. }
  51377. if (!subMesh.effect.isReady()) {
  51378. return false;
  51379. }
  51380. this._renderId = scene.getRenderId();
  51381. this._wasPreviouslyReady = true;
  51382. return true;
  51383. };
  51384. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  51385. var scene = this.getScene();
  51386. var defines = subMesh._materialDefines;
  51387. if (!defines) {
  51388. return;
  51389. }
  51390. var effect = subMesh.effect;
  51391. this._activeEffect = effect;
  51392. // Matrices
  51393. this.bindOnlyWorldMatrix(world);
  51394. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  51395. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  51396. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  51397. // Uniforms
  51398. if (this._mustRebind(scene, effect)) {
  51399. this._activeEffect.setColor3("mainColor", this.mainColor);
  51400. this._activeEffect.setColor3("lineColor", this.lineColor);
  51401. this._gridControl.x = this.gridRatio;
  51402. this._gridControl.y = Math.round(this.majorUnitFrequency);
  51403. this._gridControl.z = this.minorUnitVisibility;
  51404. this._gridControl.w = this.opacity;
  51405. this._activeEffect.setVector4("gridControl", this._gridControl);
  51406. }
  51407. // Fog
  51408. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  51409. this._afterBind(mesh, this._activeEffect);
  51410. };
  51411. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  51412. _super.prototype.dispose.call(this, forceDisposeEffect);
  51413. };
  51414. GridMaterial.prototype.clone = function (name) {
  51415. var _this = this;
  51416. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  51417. };
  51418. GridMaterial.prototype.serialize = function () {
  51419. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51420. serializationObject.customType = "BABYLON.GridMaterial";
  51421. return serializationObject;
  51422. };
  51423. GridMaterial.prototype.getClassName = function () {
  51424. return "GridMaterial";
  51425. };
  51426. GridMaterial.Parse = function (source, scene, rootUrl) {
  51427. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  51428. };
  51429. __decorate([
  51430. BABYLON.serializeAsColor3()
  51431. ], GridMaterial.prototype, "mainColor", void 0);
  51432. __decorate([
  51433. BABYLON.serializeAsColor3()
  51434. ], GridMaterial.prototype, "lineColor", void 0);
  51435. __decorate([
  51436. BABYLON.serialize()
  51437. ], GridMaterial.prototype, "gridRatio", void 0);
  51438. __decorate([
  51439. BABYLON.serialize()
  51440. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  51441. __decorate([
  51442. BABYLON.serialize()
  51443. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  51444. __decorate([
  51445. BABYLON.serialize()
  51446. ], GridMaterial.prototype, "opacity", void 0);
  51447. __decorate([
  51448. BABYLON.serialize()
  51449. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  51450. return GridMaterial;
  51451. }(BABYLON.PushMaterial));
  51452. BABYLON.GridMaterial = GridMaterial;
  51453. })(BABYLON || (BABYLON = {}));
  51454. //# sourceMappingURL=babylon.gridmaterial.js.map
  51455. BABYLON.Effect.ShadersStore['gridVertexShader'] = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}";
  51456. BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=vPosition/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";
  51457. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  51458. var BABYLON;
  51459. (function (BABYLON) {
  51460. var GLTFLoaderCoordinateSystemMode;
  51461. (function (GLTFLoaderCoordinateSystemMode) {
  51462. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  51463. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  51464. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  51465. // The glTF right-handed data is not transformed in any form and is loaded directly.
  51466. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  51467. // Sets the useRightHandedSystem flag on the scene.
  51468. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  51469. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  51470. var GLTFFileLoader = (function () {
  51471. function GLTFFileLoader() {
  51472. // V2 options
  51473. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  51474. this.name = "gltf";
  51475. this.extensions = {
  51476. ".gltf": { isBinary: false },
  51477. ".glb": { isBinary: true }
  51478. };
  51479. }
  51480. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  51481. var loaderData = GLTFFileLoader._parse(data, onError);
  51482. if (!loaderData) {
  51483. return;
  51484. }
  51485. var loader = this._getLoader(loaderData, onError);
  51486. if (!loader) {
  51487. return;
  51488. }
  51489. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  51490. };
  51491. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  51492. var loaderData = GLTFFileLoader._parse(data, onError);
  51493. if (!loaderData) {
  51494. return;
  51495. }
  51496. var loader = this._getLoader(loaderData, onError);
  51497. if (!loader) {
  51498. return;
  51499. }
  51500. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  51501. };
  51502. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  51503. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  51504. };
  51505. GLTFFileLoader._parse = function (data, onError) {
  51506. if (data instanceof ArrayBuffer) {
  51507. return GLTFFileLoader._parseBinary(data, onError);
  51508. }
  51509. try {
  51510. return {
  51511. json: JSON.parse(data),
  51512. bin: null
  51513. };
  51514. }
  51515. catch (e) {
  51516. onError(e.message);
  51517. return null;
  51518. }
  51519. };
  51520. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  51521. var loaderVersion = { major: 2, minor: 0 };
  51522. var asset = loaderData.json.asset || {};
  51523. var version = GLTFFileLoader._parseVersion(asset.version);
  51524. if (!version) {
  51525. onError("Invalid version: " + asset.version);
  51526. return null;
  51527. }
  51528. if (asset.minVersion !== undefined) {
  51529. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  51530. if (!minVersion) {
  51531. onError("Invalid minimum version: " + asset.minVersion);
  51532. return null;
  51533. }
  51534. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  51535. onError("Incompatible minimum version: " + asset.minVersion);
  51536. return null;
  51537. }
  51538. }
  51539. var createLoaders = {
  51540. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  51541. 2: GLTFFileLoader.CreateGLTFLoaderV2
  51542. };
  51543. var createLoader = createLoaders[version.major];
  51544. if (!createLoader) {
  51545. onError("Unsupported version: " + asset.version);
  51546. return null;
  51547. }
  51548. return createLoader(this);
  51549. };
  51550. GLTFFileLoader._parseBinary = function (data, onError) {
  51551. var Binary = {
  51552. Magic: 0x46546C67
  51553. };
  51554. var binaryReader = new BinaryReader(data);
  51555. var magic = binaryReader.readUint32();
  51556. if (magic !== Binary.Magic) {
  51557. onError("Unexpected magic: " + magic);
  51558. return null;
  51559. }
  51560. var version = binaryReader.readUint32();
  51561. switch (version) {
  51562. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  51563. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  51564. }
  51565. onError("Unsupported version: " + version);
  51566. return null;
  51567. };
  51568. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  51569. var ContentFormat = {
  51570. JSON: 0
  51571. };
  51572. var length = binaryReader.readUint32();
  51573. if (length != binaryReader.getLength()) {
  51574. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  51575. return null;
  51576. }
  51577. var contentLength = binaryReader.readUint32();
  51578. var contentFormat = binaryReader.readUint32();
  51579. var content;
  51580. switch (contentFormat) {
  51581. case ContentFormat.JSON:
  51582. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  51583. break;
  51584. default:
  51585. onError("Unexpected content format: " + contentFormat);
  51586. return null;
  51587. }
  51588. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  51589. var body = binaryReader.readUint8Array(bytesRemaining);
  51590. return {
  51591. json: content,
  51592. bin: body
  51593. };
  51594. };
  51595. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  51596. var ChunkFormat = {
  51597. JSON: 0x4E4F534A,
  51598. BIN: 0x004E4942
  51599. };
  51600. var length = binaryReader.readUint32();
  51601. if (length !== binaryReader.getLength()) {
  51602. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  51603. return null;
  51604. }
  51605. // JSON chunk
  51606. var chunkLength = binaryReader.readUint32();
  51607. var chunkFormat = binaryReader.readUint32();
  51608. if (chunkFormat !== ChunkFormat.JSON) {
  51609. onError("First chunk format is not JSON");
  51610. return null;
  51611. }
  51612. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  51613. // Look for BIN chunk
  51614. var bin = null;
  51615. while (binaryReader.getPosition() < binaryReader.getLength()) {
  51616. chunkLength = binaryReader.readUint32();
  51617. chunkFormat = binaryReader.readUint32();
  51618. switch (chunkFormat) {
  51619. case ChunkFormat.JSON:
  51620. onError("Unexpected JSON chunk");
  51621. return null;
  51622. case ChunkFormat.BIN:
  51623. bin = binaryReader.readUint8Array(chunkLength);
  51624. break;
  51625. default:
  51626. // ignore unrecognized chunkFormat
  51627. binaryReader.skipBytes(chunkLength);
  51628. break;
  51629. }
  51630. }
  51631. return {
  51632. json: json,
  51633. bin: bin
  51634. };
  51635. };
  51636. GLTFFileLoader._parseVersion = function (version) {
  51637. if (!version) {
  51638. return null;
  51639. }
  51640. var parts = version.split(".");
  51641. if (parts.length != 2) {
  51642. return null;
  51643. }
  51644. var major = +parts[0];
  51645. if (isNaN(major)) {
  51646. return null;
  51647. }
  51648. var minor = +parts[1];
  51649. if (isNaN(minor)) {
  51650. return null;
  51651. }
  51652. return {
  51653. major: major,
  51654. minor: minor
  51655. };
  51656. };
  51657. GLTFFileLoader._compareVersion = function (a, b) {
  51658. if (a.major > b.major)
  51659. return 1;
  51660. if (a.major < b.major)
  51661. return -1;
  51662. if (a.minor > b.minor)
  51663. return 1;
  51664. if (a.minor < b.minor)
  51665. return -1;
  51666. return 0;
  51667. };
  51668. GLTFFileLoader._decodeBufferToText = function (view) {
  51669. var result = "";
  51670. var length = view.byteLength;
  51671. for (var i = 0; i < length; ++i) {
  51672. result += String.fromCharCode(view[i]);
  51673. }
  51674. return result;
  51675. };
  51676. // V1 options
  51677. GLTFFileLoader.HomogeneousCoordinates = false;
  51678. GLTFFileLoader.IncrementalLoading = true;
  51679. return GLTFFileLoader;
  51680. }());
  51681. BABYLON.GLTFFileLoader = GLTFFileLoader;
  51682. var BinaryReader = (function () {
  51683. function BinaryReader(arrayBuffer) {
  51684. this._arrayBuffer = arrayBuffer;
  51685. this._dataView = new DataView(arrayBuffer);
  51686. this._byteOffset = 0;
  51687. }
  51688. BinaryReader.prototype.getPosition = function () {
  51689. return this._byteOffset;
  51690. };
  51691. BinaryReader.prototype.getLength = function () {
  51692. return this._arrayBuffer.byteLength;
  51693. };
  51694. BinaryReader.prototype.readUint32 = function () {
  51695. var value = this._dataView.getUint32(this._byteOffset, true);
  51696. this._byteOffset += 4;
  51697. return value;
  51698. };
  51699. BinaryReader.prototype.readUint8Array = function (length) {
  51700. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  51701. this._byteOffset += length;
  51702. return value;
  51703. };
  51704. BinaryReader.prototype.skipBytes = function (length) {
  51705. this._byteOffset += length;
  51706. };
  51707. return BinaryReader;
  51708. }());
  51709. if (BABYLON.SceneLoader) {
  51710. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  51711. }
  51712. })(BABYLON || (BABYLON = {}));
  51713. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  51714. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  51715. var BABYLON;
  51716. (function (BABYLON) {
  51717. var GLTF1;
  51718. (function (GLTF1) {
  51719. /**
  51720. * Enums
  51721. */
  51722. var EComponentType;
  51723. (function (EComponentType) {
  51724. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  51725. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  51726. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  51727. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  51728. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  51729. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  51730. var EShaderType;
  51731. (function (EShaderType) {
  51732. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  51733. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  51734. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  51735. var EParameterType;
  51736. (function (EParameterType) {
  51737. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  51738. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  51739. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  51740. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  51741. EParameterType[EParameterType["INT"] = 5124] = "INT";
  51742. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  51743. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  51744. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  51745. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  51746. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  51747. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  51748. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  51749. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  51750. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  51751. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  51752. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  51753. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  51754. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  51755. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  51756. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  51757. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  51758. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  51759. var ETextureWrapMode;
  51760. (function (ETextureWrapMode) {
  51761. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  51762. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  51763. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  51764. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  51765. var ETextureFilterType;
  51766. (function (ETextureFilterType) {
  51767. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  51768. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  51769. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  51770. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  51771. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  51772. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  51773. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  51774. var ETextureFormat;
  51775. (function (ETextureFormat) {
  51776. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  51777. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  51778. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  51779. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  51780. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  51781. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  51782. var ECullingType;
  51783. (function (ECullingType) {
  51784. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  51785. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  51786. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  51787. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  51788. var EBlendingFunction;
  51789. (function (EBlendingFunction) {
  51790. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  51791. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  51792. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  51793. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  51794. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  51795. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  51796. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  51797. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  51798. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  51799. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  51800. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  51801. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  51802. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  51803. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  51804. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  51805. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  51806. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  51807. })(BABYLON || (BABYLON = {}));
  51808. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  51809. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  51810. var BABYLON;
  51811. (function (BABYLON) {
  51812. var GLTF1;
  51813. (function (GLTF1) {
  51814. /**
  51815. * Tokenizer. Used for shaders compatibility
  51816. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  51817. */
  51818. var ETokenType;
  51819. (function (ETokenType) {
  51820. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  51821. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  51822. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  51823. })(ETokenType || (ETokenType = {}));
  51824. var Tokenizer = (function () {
  51825. function Tokenizer(toParse) {
  51826. this._pos = 0;
  51827. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  51828. this._toParse = toParse;
  51829. this._maxPos = toParse.length;
  51830. }
  51831. Tokenizer.prototype.getNextToken = function () {
  51832. if (this.isEnd())
  51833. return ETokenType.END_OF_INPUT;
  51834. this.currentString = this.read();
  51835. this.currentToken = ETokenType.UNKNOWN;
  51836. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  51837. this.currentToken = ETokenType.IDENTIFIER;
  51838. this.currentIdentifier = this.currentString;
  51839. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  51840. this.currentIdentifier += this.currentString;
  51841. this.forward();
  51842. }
  51843. }
  51844. return this.currentToken;
  51845. };
  51846. Tokenizer.prototype.peek = function () {
  51847. return this._toParse[this._pos];
  51848. };
  51849. Tokenizer.prototype.read = function () {
  51850. return this._toParse[this._pos++];
  51851. };
  51852. Tokenizer.prototype.forward = function () {
  51853. this._pos++;
  51854. };
  51855. Tokenizer.prototype.isEnd = function () {
  51856. return this._pos >= this._maxPos;
  51857. };
  51858. return Tokenizer;
  51859. }());
  51860. /**
  51861. * Values
  51862. */
  51863. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  51864. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  51865. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  51866. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  51867. /**
  51868. * Parse
  51869. */
  51870. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  51871. for (var buf in parsedBuffers) {
  51872. var parsedBuffer = parsedBuffers[buf];
  51873. gltfRuntime.buffers[buf] = parsedBuffer;
  51874. gltfRuntime.buffersCount++;
  51875. }
  51876. };
  51877. var parseShaders = function (parsedShaders, gltfRuntime) {
  51878. for (var sha in parsedShaders) {
  51879. var parsedShader = parsedShaders[sha];
  51880. gltfRuntime.shaders[sha] = parsedShader;
  51881. gltfRuntime.shaderscount++;
  51882. }
  51883. };
  51884. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  51885. for (var object in parsedObjects) {
  51886. var parsedObject = parsedObjects[object];
  51887. gltfRuntime[runtimeProperty][object] = parsedObject;
  51888. }
  51889. };
  51890. /**
  51891. * Utils
  51892. */
  51893. var normalizeUVs = function (buffer) {
  51894. if (!buffer) {
  51895. return;
  51896. }
  51897. for (var i = 0; i < buffer.length / 2; i++) {
  51898. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  51899. }
  51900. };
  51901. var replaceInString = function (str, searchValue, replaceValue) {
  51902. while (str.indexOf(searchValue) !== -1) {
  51903. str = str.replace(searchValue, replaceValue);
  51904. }
  51905. return str;
  51906. };
  51907. var getAttribute = function (attributeParameter) {
  51908. if (attributeParameter.semantic === "NORMAL") {
  51909. return "normal";
  51910. }
  51911. else if (attributeParameter.semantic === "POSITION") {
  51912. return "position";
  51913. }
  51914. else if (attributeParameter.semantic === "JOINT") {
  51915. return "matricesIndices";
  51916. }
  51917. else if (attributeParameter.semantic === "WEIGHT") {
  51918. return "matricesWeights";
  51919. }
  51920. else if (attributeParameter.semantic === "COLOR") {
  51921. return "color";
  51922. }
  51923. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  51924. var channel = Number(attributeParameter.semantic.split("_")[1]);
  51925. return "uv" + (channel === 0 ? "" : channel + 1);
  51926. }
  51927. };
  51928. /**
  51929. * Returns the animation path (glTF -> Babylon)
  51930. */
  51931. var getAnimationPath = function (path) {
  51932. var index = glTFAnimationPaths.indexOf(path);
  51933. if (index !== -1) {
  51934. return babylonAnimationPaths[index];
  51935. }
  51936. return path;
  51937. };
  51938. /**
  51939. * Loads and creates animations
  51940. */
  51941. var loadAnimations = function (gltfRuntime) {
  51942. for (var anim in gltfRuntime.animations) {
  51943. var animation = gltfRuntime.animations[anim];
  51944. var lastAnimation = null;
  51945. for (var i = 0; i < animation.channels.length; i++) {
  51946. // Get parameters and load buffers
  51947. var channel = animation.channels[i];
  51948. var sampler = animation.samplers[channel.sampler];
  51949. if (!sampler) {
  51950. continue;
  51951. }
  51952. var inputData = null;
  51953. var outputData = null;
  51954. if (animation.parameters) {
  51955. inputData = animation.parameters[sampler.input];
  51956. outputData = animation.parameters[sampler.output];
  51957. }
  51958. else {
  51959. inputData = sampler.input;
  51960. outputData = sampler.output;
  51961. }
  51962. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  51963. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  51964. var targetID = channel.target.id;
  51965. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  51966. if (targetNode === null) {
  51967. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  51968. }
  51969. if (targetNode === null) {
  51970. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  51971. continue;
  51972. }
  51973. var isBone = targetNode instanceof BABYLON.Bone;
  51974. // Get target path (position, rotation or scaling)
  51975. var targetPath = channel.target.path;
  51976. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  51977. if (targetPathIndex !== -1) {
  51978. targetPath = babylonAnimationPaths[targetPathIndex];
  51979. }
  51980. // Determine animation type
  51981. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  51982. if (!isBone) {
  51983. if (targetPath === "rotationQuaternion") {
  51984. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  51985. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  51986. }
  51987. else {
  51988. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  51989. }
  51990. }
  51991. // Create animation and key frames
  51992. var babylonAnimation = null;
  51993. var keys = [];
  51994. var arrayOffset = 0;
  51995. var modifyKey = false;
  51996. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  51997. babylonAnimation = lastAnimation;
  51998. modifyKey = true;
  51999. }
  52000. if (!modifyKey) {
  52001. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52002. }
  52003. // For each frame
  52004. for (var j = 0; j < bufferInput.length; j++) {
  52005. var value = null;
  52006. if (targetPath === "rotationQuaternion") {
  52007. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  52008. arrayOffset += 4;
  52009. }
  52010. else {
  52011. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  52012. arrayOffset += 3;
  52013. }
  52014. if (isBone) {
  52015. var bone = targetNode;
  52016. var translation = BABYLON.Vector3.Zero();
  52017. var rotationQuaternion = new BABYLON.Quaternion();
  52018. var scaling = BABYLON.Vector3.Zero();
  52019. // Warning on decompose
  52020. var mat = bone.getBaseMatrix();
  52021. if (modifyKey) {
  52022. mat = lastAnimation.getKeys()[j].value;
  52023. }
  52024. mat.decompose(scaling, rotationQuaternion, translation);
  52025. if (targetPath === "position") {
  52026. translation = value;
  52027. }
  52028. else if (targetPath === "rotationQuaternion") {
  52029. rotationQuaternion = value;
  52030. }
  52031. else {
  52032. scaling = value;
  52033. }
  52034. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  52035. }
  52036. if (!modifyKey) {
  52037. keys.push({
  52038. frame: bufferInput[j],
  52039. value: value
  52040. });
  52041. }
  52042. else {
  52043. lastAnimation.getKeys()[j].value = value;
  52044. }
  52045. }
  52046. // Finish
  52047. if (!modifyKey) {
  52048. babylonAnimation.setKeys(keys);
  52049. targetNode.animations.push(babylonAnimation);
  52050. }
  52051. lastAnimation = babylonAnimation;
  52052. gltfRuntime.scene.stopAnimation(targetNode);
  52053. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  52054. }
  52055. }
  52056. };
  52057. /**
  52058. * Returns the bones transformation matrix
  52059. */
  52060. var configureBoneTransformation = function (node) {
  52061. var mat = null;
  52062. if (node.translation || node.rotation || node.scale) {
  52063. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  52064. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  52065. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  52066. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  52067. }
  52068. else {
  52069. mat = BABYLON.Matrix.FromArray(node.matrix);
  52070. }
  52071. return mat;
  52072. };
  52073. /**
  52074. * Returns the parent bone
  52075. */
  52076. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  52077. // Try to find
  52078. for (var i = 0; i < newSkeleton.bones.length; i++) {
  52079. if (newSkeleton.bones[i].name === jointName) {
  52080. return newSkeleton.bones[i];
  52081. }
  52082. }
  52083. // Not found, search in gltf nodes
  52084. var nodes = gltfRuntime.nodes;
  52085. for (var nde in nodes) {
  52086. var node = nodes[nde];
  52087. if (!node.jointName) {
  52088. continue;
  52089. }
  52090. var children = node.children;
  52091. for (var i = 0; i < children.length; i++) {
  52092. var child = gltfRuntime.nodes[children[i]];
  52093. if (!child.jointName) {
  52094. continue;
  52095. }
  52096. if (child.jointName === jointName) {
  52097. var mat = configureBoneTransformation(node);
  52098. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  52099. bone.id = nde;
  52100. return bone;
  52101. }
  52102. }
  52103. }
  52104. return null;
  52105. };
  52106. /**
  52107. * Returns the appropriate root node
  52108. */
  52109. var getNodeToRoot = function (nodesToRoot, id) {
  52110. for (var i = 0; i < nodesToRoot.length; i++) {
  52111. var nodeToRoot = nodesToRoot[i];
  52112. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  52113. var child = nodeToRoot.node.children[j];
  52114. if (child === id) {
  52115. return nodeToRoot.bone;
  52116. }
  52117. }
  52118. }
  52119. return null;
  52120. };
  52121. /**
  52122. * Returns the node with the joint name
  52123. */
  52124. var getJointNode = function (gltfRuntime, jointName) {
  52125. var nodes = gltfRuntime.nodes;
  52126. var node = nodes[jointName];
  52127. if (node) {
  52128. return {
  52129. node: node,
  52130. id: jointName
  52131. };
  52132. }
  52133. for (var nde in nodes) {
  52134. node = nodes[nde];
  52135. if (node.jointName === jointName) {
  52136. return {
  52137. node: node,
  52138. id: nde
  52139. };
  52140. }
  52141. }
  52142. return null;
  52143. };
  52144. /**
  52145. * Checks if a nodes is in joints
  52146. */
  52147. var nodeIsInJoints = function (skins, id) {
  52148. for (var i = 0; i < skins.jointNames.length; i++) {
  52149. if (skins.jointNames[i] === id) {
  52150. return true;
  52151. }
  52152. }
  52153. return false;
  52154. };
  52155. /**
  52156. * Fills the nodes to root for bones and builds hierarchy
  52157. */
  52158. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  52159. // Creates nodes for root
  52160. for (var nde in gltfRuntime.nodes) {
  52161. var node = gltfRuntime.nodes[nde];
  52162. var id = nde;
  52163. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  52164. continue;
  52165. }
  52166. // Create node to root bone
  52167. var mat = configureBoneTransformation(node);
  52168. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  52169. bone.id = id;
  52170. nodesToRoot.push({ bone: bone, node: node, id: id });
  52171. }
  52172. // Parenting
  52173. for (var i = 0; i < nodesToRoot.length; i++) {
  52174. var nodeToRoot = nodesToRoot[i];
  52175. var children = nodeToRoot.node.children;
  52176. for (var j = 0; j < children.length; j++) {
  52177. var child = null;
  52178. for (var k = 0; k < nodesToRoot.length; k++) {
  52179. if (nodesToRoot[k].id === children[j]) {
  52180. child = nodesToRoot[k];
  52181. break;
  52182. }
  52183. }
  52184. if (child) {
  52185. child.bone._parent = nodeToRoot.bone;
  52186. nodeToRoot.bone.children.push(child.bone);
  52187. }
  52188. }
  52189. }
  52190. };
  52191. var printMat = function (m) {
  52192. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  52193. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  52194. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  52195. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  52196. };
  52197. /**
  52198. * Imports a skeleton
  52199. */
  52200. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  52201. if (!newSkeleton) {
  52202. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  52203. }
  52204. if (!skins.babylonSkeleton) {
  52205. return newSkeleton;
  52206. }
  52207. // Matrices
  52208. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  52209. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52210. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  52211. // Find the root bones
  52212. var nodesToRoot = [];
  52213. var nodesToRootToAdd = [];
  52214. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  52215. newSkeleton.bones = [];
  52216. // Joints
  52217. for (var i = 0; i < skins.jointNames.length; i++) {
  52218. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  52219. var node = jointNode.node;
  52220. if (!node) {
  52221. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  52222. continue;
  52223. }
  52224. var id = jointNode.id;
  52225. // Optimize, if the bone already exists...
  52226. var existingBone = gltfRuntime.scene.getBoneByID(id);
  52227. if (existingBone) {
  52228. newSkeleton.bones.push(existingBone);
  52229. continue;
  52230. }
  52231. // Search for parent bone
  52232. var foundBone = false;
  52233. var parentBone = null;
  52234. for (var j = 0; j < i; j++) {
  52235. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  52236. if (!joint) {
  52237. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  52238. continue;
  52239. }
  52240. var children = joint.children;
  52241. if (!children) {
  52242. continue;
  52243. }
  52244. foundBone = false;
  52245. for (var k = 0; k < children.length; k++) {
  52246. if (children[k] === id) {
  52247. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  52248. foundBone = true;
  52249. break;
  52250. }
  52251. }
  52252. if (foundBone) {
  52253. break;
  52254. }
  52255. }
  52256. // Create bone
  52257. var mat = configureBoneTransformation(node);
  52258. if (!parentBone && nodesToRoot.length > 0) {
  52259. parentBone = getNodeToRoot(nodesToRoot, id);
  52260. if (parentBone) {
  52261. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  52262. nodesToRootToAdd.push(parentBone);
  52263. }
  52264. }
  52265. }
  52266. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  52267. bone.id = id;
  52268. }
  52269. // Polish
  52270. var bones = newSkeleton.bones;
  52271. newSkeleton.bones = [];
  52272. for (var i = 0; i < skins.jointNames.length; i++) {
  52273. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  52274. if (!jointNode) {
  52275. continue;
  52276. }
  52277. for (var j = 0; j < bones.length; j++) {
  52278. if (bones[j].id === jointNode.id) {
  52279. newSkeleton.bones.push(bones[j]);
  52280. break;
  52281. }
  52282. }
  52283. }
  52284. newSkeleton.prepare();
  52285. // Finish
  52286. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  52287. newSkeleton.bones.push(nodesToRootToAdd[i]);
  52288. }
  52289. return newSkeleton;
  52290. };
  52291. /**
  52292. * Imports a mesh and its geometries
  52293. */
  52294. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  52295. if (!newMesh) {
  52296. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  52297. newMesh.id = id;
  52298. }
  52299. if (!node.babylonNode) {
  52300. return newMesh;
  52301. }
  52302. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  52303. if (!newMesh.material) {
  52304. newMesh.material = multiMat;
  52305. }
  52306. var vertexData = new BABYLON.VertexData();
  52307. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  52308. var verticesStarts = [];
  52309. var verticesCounts = [];
  52310. var indexStarts = [];
  52311. var indexCounts = [];
  52312. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  52313. var meshID = meshes[meshIndex];
  52314. var mesh = gltfRuntime.meshes[meshID];
  52315. if (!mesh) {
  52316. continue;
  52317. }
  52318. // Positions, normals and UVs
  52319. for (var i = 0; i < mesh.primitives.length; i++) {
  52320. // Temporary vertex data
  52321. var tempVertexData = new BABYLON.VertexData();
  52322. var primitive = mesh.primitives[i];
  52323. if (primitive.mode !== 4) {
  52324. // continue;
  52325. }
  52326. var attributes = primitive.attributes;
  52327. var accessor = null;
  52328. var buffer = null;
  52329. // Set positions, normal and uvs
  52330. for (var semantic in attributes) {
  52331. // Link accessor and buffer view
  52332. accessor = gltfRuntime.accessors[attributes[semantic]];
  52333. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52334. if (semantic === "NORMAL") {
  52335. tempVertexData.normals = new Float32Array(buffer.length);
  52336. tempVertexData.normals.set(buffer);
  52337. }
  52338. else if (semantic === "POSITION") {
  52339. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  52340. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  52341. for (var j = 0; j < buffer.length; j += 4) {
  52342. tempVertexData.positions[j] = buffer[j];
  52343. tempVertexData.positions[j + 1] = buffer[j + 1];
  52344. tempVertexData.positions[j + 2] = buffer[j + 2];
  52345. }
  52346. }
  52347. else {
  52348. tempVertexData.positions = new Float32Array(buffer.length);
  52349. tempVertexData.positions.set(buffer);
  52350. }
  52351. verticesCounts.push(tempVertexData.positions.length);
  52352. }
  52353. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  52354. var channel = Number(semantic.split("_")[1]);
  52355. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  52356. var uvs = new Float32Array(buffer.length);
  52357. uvs.set(buffer);
  52358. normalizeUVs(uvs);
  52359. tempVertexData.set(uvs, uvKind);
  52360. }
  52361. else if (semantic === "JOINT") {
  52362. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  52363. tempVertexData.matricesIndices.set(buffer);
  52364. }
  52365. else if (semantic === "WEIGHT") {
  52366. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  52367. tempVertexData.matricesWeights.set(buffer);
  52368. }
  52369. else if (semantic === "COLOR") {
  52370. tempVertexData.colors = new Float32Array(buffer.length);
  52371. tempVertexData.colors.set(buffer);
  52372. }
  52373. }
  52374. // Indices
  52375. accessor = gltfRuntime.accessors[primitive.indices];
  52376. if (accessor) {
  52377. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52378. tempVertexData.indices = new Int32Array(buffer.length);
  52379. tempVertexData.indices.set(buffer);
  52380. indexCounts.push(tempVertexData.indices.length);
  52381. }
  52382. else {
  52383. // Set indices on the fly
  52384. var indices = [];
  52385. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  52386. indices.push(j);
  52387. }
  52388. tempVertexData.indices = new Int32Array(indices);
  52389. indexCounts.push(tempVertexData.indices.length);
  52390. }
  52391. vertexData.merge(tempVertexData);
  52392. tempVertexData = undefined;
  52393. // Sub material
  52394. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  52395. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  52396. // Update vertices start and index start
  52397. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  52398. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  52399. }
  52400. }
  52401. // Apply geometry
  52402. geometry.setAllVerticesData(vertexData, false);
  52403. newMesh.computeWorldMatrix(true);
  52404. // Apply submeshes
  52405. newMesh.subMeshes = [];
  52406. var index = 0;
  52407. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  52408. var meshID = meshes[meshIndex];
  52409. var mesh = gltfRuntime.meshes[meshID];
  52410. if (!mesh) {
  52411. continue;
  52412. }
  52413. for (var i = 0; i < mesh.primitives.length; i++) {
  52414. if (mesh.primitives[i].mode !== 4) {
  52415. //continue;
  52416. }
  52417. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  52418. index++;
  52419. }
  52420. }
  52421. // Finish
  52422. return newMesh;
  52423. };
  52424. /**
  52425. * Configure node transformation from position, rotation and scaling
  52426. */
  52427. var configureNode = function (newNode, position, rotation, scaling) {
  52428. if (newNode.position) {
  52429. newNode.position = position;
  52430. }
  52431. if (newNode.rotationQuaternion || newNode.rotation) {
  52432. newNode.rotationQuaternion = rotation;
  52433. }
  52434. if (newNode.scaling) {
  52435. newNode.scaling = scaling;
  52436. }
  52437. };
  52438. /**
  52439. * Configures node from transformation matrix
  52440. */
  52441. var configureNodeFromMatrix = function (newNode, node, parent) {
  52442. if (node.matrix) {
  52443. var position = new BABYLON.Vector3(0, 0, 0);
  52444. var rotation = new BABYLON.Quaternion();
  52445. var scaling = new BABYLON.Vector3(0, 0, 0);
  52446. var mat = BABYLON.Matrix.FromArray(node.matrix);
  52447. mat.decompose(scaling, rotation, position);
  52448. configureNode(newNode, position, rotation, scaling);
  52449. }
  52450. else {
  52451. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  52452. }
  52453. newNode.computeWorldMatrix(true);
  52454. };
  52455. /**
  52456. * Imports a node
  52457. */
  52458. var importNode = function (gltfRuntime, node, id, parent) {
  52459. var lastNode = null;
  52460. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  52461. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  52462. return null;
  52463. }
  52464. }
  52465. // Meshes
  52466. if (node.skin) {
  52467. if (node.meshes) {
  52468. var skin = gltfRuntime.skins[node.skin];
  52469. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  52470. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  52471. if (newMesh.skeleton === null) {
  52472. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  52473. if (!skin.babylonSkeleton) {
  52474. skin.babylonSkeleton = newMesh.skeleton;
  52475. }
  52476. }
  52477. lastNode = newMesh;
  52478. }
  52479. }
  52480. else if (node.meshes) {
  52481. /**
  52482. * Improve meshes property
  52483. */
  52484. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  52485. lastNode = newMesh;
  52486. }
  52487. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  52488. var light = gltfRuntime.lights[node.light];
  52489. if (light) {
  52490. if (light.type === "ambient") {
  52491. var ambienLight = light[light.type];
  52492. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52493. hemiLight.name = node.name;
  52494. if (ambienLight.color) {
  52495. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  52496. }
  52497. lastNode = hemiLight;
  52498. }
  52499. else if (light.type === "directional") {
  52500. var directionalLight = light[light.type];
  52501. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52502. dirLight.name = node.name;
  52503. if (directionalLight.color) {
  52504. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  52505. }
  52506. lastNode = dirLight;
  52507. }
  52508. else if (light.type === "point") {
  52509. var pointLight = light[light.type];
  52510. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52511. ptLight.name = node.name;
  52512. if (pointLight.color) {
  52513. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  52514. }
  52515. lastNode = ptLight;
  52516. }
  52517. else if (light.type === "spot") {
  52518. var spotLight = light[light.type];
  52519. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  52520. spLight.name = node.name;
  52521. if (spotLight.color) {
  52522. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  52523. }
  52524. if (spotLight.fallOfAngle) {
  52525. spLight.angle = spotLight.fallOfAngle;
  52526. }
  52527. if (spotLight.fallOffExponent) {
  52528. spLight.exponent = spotLight.fallOffExponent;
  52529. }
  52530. lastNode = spLight;
  52531. }
  52532. }
  52533. }
  52534. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  52535. var camera = gltfRuntime.cameras[node.camera];
  52536. if (camera) {
  52537. if (camera.type === "orthographic") {
  52538. var orthographicCamera = camera[camera.type];
  52539. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52540. orthoCamera.name = node.name;
  52541. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  52542. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  52543. lastNode = orthoCamera;
  52544. }
  52545. else if (camera.type === "perspective") {
  52546. var perspectiveCamera = camera[camera.type];
  52547. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52548. persCamera.name = node.name;
  52549. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  52550. if (!perspectiveCamera.aspectRatio) {
  52551. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  52552. }
  52553. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  52554. persCamera.maxZ = perspectiveCamera.zfar;
  52555. persCamera.minZ = perspectiveCamera.znear;
  52556. }
  52557. lastNode = persCamera;
  52558. }
  52559. }
  52560. }
  52561. // Empty node
  52562. if (!node.jointName) {
  52563. if (node.babylonNode) {
  52564. return node.babylonNode;
  52565. }
  52566. else if (lastNode === null) {
  52567. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  52568. node.babylonNode = dummy;
  52569. lastNode = dummy;
  52570. }
  52571. }
  52572. if (lastNode !== null) {
  52573. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  52574. configureNodeFromMatrix(lastNode, node, parent);
  52575. }
  52576. else {
  52577. var translation = node.translation || [0, 0, 0];
  52578. var rotation = node.rotation || [0, 0, 0, 1];
  52579. var scale = node.scale || [1, 1, 1];
  52580. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  52581. }
  52582. lastNode.updateCache(true);
  52583. node.babylonNode = lastNode;
  52584. }
  52585. return lastNode;
  52586. };
  52587. /**
  52588. * Traverses nodes and creates them
  52589. */
  52590. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  52591. var node = gltfRuntime.nodes[id];
  52592. var newNode = null;
  52593. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  52594. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  52595. meshIncluded = true;
  52596. }
  52597. else {
  52598. meshIncluded = false;
  52599. }
  52600. }
  52601. else {
  52602. meshIncluded = true;
  52603. }
  52604. if (!node.jointName && meshIncluded) {
  52605. newNode = importNode(gltfRuntime, node, id, parent);
  52606. if (newNode !== null) {
  52607. newNode.id = id;
  52608. newNode.parent = parent;
  52609. }
  52610. }
  52611. if (node.children) {
  52612. for (var i = 0; i < node.children.length; i++) {
  52613. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  52614. }
  52615. }
  52616. };
  52617. /**
  52618. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  52619. */
  52620. var postLoad = function (gltfRuntime) {
  52621. // Nodes
  52622. var currentScene = gltfRuntime.currentScene;
  52623. if (currentScene) {
  52624. for (var i = 0; i < currentScene.nodes.length; i++) {
  52625. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52626. }
  52627. }
  52628. else {
  52629. for (var thing in gltfRuntime.scenes) {
  52630. currentScene = gltfRuntime.scenes[thing];
  52631. for (var i = 0; i < currentScene.nodes.length; i++) {
  52632. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52633. }
  52634. }
  52635. }
  52636. // Set animations
  52637. loadAnimations(gltfRuntime);
  52638. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  52639. var skeleton = gltfRuntime.scene.skeletons[i];
  52640. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  52641. }
  52642. };
  52643. /**
  52644. * onBind shaderrs callback to set uniforms and matrices
  52645. */
  52646. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  52647. var materialValues = material.values || technique.parameters;
  52648. for (var unif in unTreatedUniforms) {
  52649. var uniform = unTreatedUniforms[unif];
  52650. var type = uniform.type;
  52651. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  52652. if (uniform.semantic && !uniform.source && !uniform.node) {
  52653. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  52654. }
  52655. else if (uniform.semantic && (uniform.source || uniform.node)) {
  52656. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  52657. if (source === null) {
  52658. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  52659. }
  52660. if (source === null) {
  52661. continue;
  52662. }
  52663. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  52664. }
  52665. }
  52666. else {
  52667. var value = materialValues[technique.uniforms[unif]];
  52668. if (!value) {
  52669. continue;
  52670. }
  52671. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  52672. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  52673. if (texture === null || texture === undefined) {
  52674. continue;
  52675. }
  52676. shaderMaterial.getEffect().setTexture(unif, texture);
  52677. }
  52678. else {
  52679. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  52680. }
  52681. }
  52682. }
  52683. onSuccess(shaderMaterial);
  52684. };
  52685. /**
  52686. * Prepare uniforms to send the only one time
  52687. * Loads the appropriate textures
  52688. */
  52689. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  52690. var materialValues = material.values || technique.parameters;
  52691. var techniqueUniforms = technique.uniforms;
  52692. /**
  52693. * Prepare values here (not matrices)
  52694. */
  52695. for (var unif in unTreatedUniforms) {
  52696. var uniform = unTreatedUniforms[unif];
  52697. var type = uniform.type;
  52698. var value = materialValues[techniqueUniforms[unif]];
  52699. if (value === undefined) {
  52700. // In case the value is the same for all materials
  52701. value = uniform.value;
  52702. }
  52703. if (!value) {
  52704. continue;
  52705. }
  52706. var onLoadTexture = function (uniformName) {
  52707. return function (texture) {
  52708. if (uniform.value) {
  52709. // Static uniform
  52710. shaderMaterial.setTexture(uniformName, texture);
  52711. delete unTreatedUniforms[uniformName];
  52712. }
  52713. };
  52714. };
  52715. // Texture (sampler2D)
  52716. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  52717. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  52718. }
  52719. else {
  52720. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  52721. // Static uniform
  52722. delete unTreatedUniforms[unif];
  52723. }
  52724. }
  52725. }
  52726. };
  52727. /**
  52728. * Shader compilation failed
  52729. */
  52730. var onShaderCompileError = function (program, shaderMaterial, onError) {
  52731. return function (effect, error) {
  52732. shaderMaterial.dispose(true);
  52733. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  52734. };
  52735. };
  52736. /**
  52737. * Shader compilation success
  52738. */
  52739. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  52740. return function (_) {
  52741. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  52742. shaderMaterial.onBind = function (mesh) {
  52743. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  52744. };
  52745. };
  52746. };
  52747. /**
  52748. * Returns the appropriate uniform if already handled by babylon
  52749. */
  52750. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  52751. for (var unif in technique.uniforms) {
  52752. var uniform = technique.uniforms[unif];
  52753. var uniformParameter = technique.parameters[uniform];
  52754. if (tokenizer.currentIdentifier === unif) {
  52755. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  52756. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  52757. if (transformIndex !== -1) {
  52758. delete unTreatedUniforms[unif];
  52759. return babylonTransforms[transformIndex];
  52760. }
  52761. }
  52762. }
  52763. }
  52764. return tokenizer.currentIdentifier;
  52765. };
  52766. /**
  52767. * All shaders loaded. Create materials one by one
  52768. */
  52769. var importMaterials = function (gltfRuntime) {
  52770. // Create materials
  52771. for (var mat in gltfRuntime.materials) {
  52772. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  52773. }
  52774. };
  52775. /**
  52776. * Implementation of the base glTF spec
  52777. */
  52778. var GLTFLoaderBase = (function () {
  52779. function GLTFLoaderBase() {
  52780. }
  52781. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  52782. var gltfRuntime = {
  52783. extensions: {},
  52784. accessors: {},
  52785. buffers: {},
  52786. bufferViews: {},
  52787. meshes: {},
  52788. lights: {},
  52789. cameras: {},
  52790. nodes: {},
  52791. images: {},
  52792. textures: {},
  52793. shaders: {},
  52794. programs: {},
  52795. samplers: {},
  52796. techniques: {},
  52797. materials: {},
  52798. animations: {},
  52799. skins: {},
  52800. extensionsUsed: [],
  52801. scenes: {},
  52802. buffersCount: 0,
  52803. shaderscount: 0,
  52804. scene: scene,
  52805. rootUrl: rootUrl,
  52806. loadedBufferCount: 0,
  52807. loadedBufferViews: {},
  52808. loadedShaderCount: 0,
  52809. importOnlyMeshes: false,
  52810. dummyNodes: []
  52811. };
  52812. // Parse
  52813. if (parsedData.extensions) {
  52814. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  52815. }
  52816. if (parsedData.extensionsUsed) {
  52817. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  52818. }
  52819. if (parsedData.buffers) {
  52820. parseBuffers(parsedData.buffers, gltfRuntime);
  52821. }
  52822. if (parsedData.bufferViews) {
  52823. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  52824. }
  52825. if (parsedData.accessors) {
  52826. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  52827. }
  52828. if (parsedData.meshes) {
  52829. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  52830. }
  52831. if (parsedData.lights) {
  52832. parseObject(parsedData.lights, "lights", gltfRuntime);
  52833. }
  52834. if (parsedData.cameras) {
  52835. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  52836. }
  52837. if (parsedData.nodes) {
  52838. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  52839. }
  52840. if (parsedData.images) {
  52841. parseObject(parsedData.images, "images", gltfRuntime);
  52842. }
  52843. if (parsedData.textures) {
  52844. parseObject(parsedData.textures, "textures", gltfRuntime);
  52845. }
  52846. if (parsedData.shaders) {
  52847. parseShaders(parsedData.shaders, gltfRuntime);
  52848. }
  52849. if (parsedData.programs) {
  52850. parseObject(parsedData.programs, "programs", gltfRuntime);
  52851. }
  52852. if (parsedData.samplers) {
  52853. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  52854. }
  52855. if (parsedData.techniques) {
  52856. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  52857. }
  52858. if (parsedData.materials) {
  52859. parseObject(parsedData.materials, "materials", gltfRuntime);
  52860. }
  52861. if (parsedData.animations) {
  52862. parseObject(parsedData.animations, "animations", gltfRuntime);
  52863. }
  52864. if (parsedData.skins) {
  52865. parseObject(parsedData.skins, "skins", gltfRuntime);
  52866. }
  52867. if (parsedData.scenes) {
  52868. gltfRuntime.scenes = parsedData.scenes;
  52869. }
  52870. if (parsedData.scene && parsedData.scenes) {
  52871. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  52872. }
  52873. return gltfRuntime;
  52874. };
  52875. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  52876. var buffer = gltfRuntime.buffers[id];
  52877. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  52878. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  52879. }
  52880. else {
  52881. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  52882. onError(request.status + " " + request.statusText);
  52883. });
  52884. }
  52885. };
  52886. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  52887. var texture = gltfRuntime.textures[id];
  52888. if (!texture || !texture.source) {
  52889. onError(null);
  52890. return;
  52891. }
  52892. if (texture.babylonTexture) {
  52893. onSuccess(null);
  52894. return;
  52895. }
  52896. var source = gltfRuntime.images[texture.source];
  52897. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  52898. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  52899. }
  52900. else {
  52901. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  52902. onError(request.status + " " + request.statusText);
  52903. });
  52904. }
  52905. };
  52906. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  52907. var texture = gltfRuntime.textures[id];
  52908. if (texture.babylonTexture) {
  52909. onSuccess(texture.babylonTexture);
  52910. return;
  52911. }
  52912. var sampler = gltfRuntime.samplers[texture.sampler];
  52913. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  52914. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  52915. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  52916. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  52917. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  52918. var blob = new Blob([buffer]);
  52919. var blobURL = URL.createObjectURL(blob);
  52920. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  52921. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  52922. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  52923. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  52924. newTexture.name = id;
  52925. texture.babylonTexture = newTexture;
  52926. onSuccess(newTexture);
  52927. };
  52928. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  52929. var shader = gltfRuntime.shaders[id];
  52930. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  52931. var shaderString = atob(shader.uri.split(",")[1]);
  52932. onSuccess(shaderString);
  52933. }
  52934. else {
  52935. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  52936. onError(request.status + " " + request.statusText);
  52937. });
  52938. }
  52939. };
  52940. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  52941. var material = gltfRuntime.materials[id];
  52942. var technique = gltfRuntime.techniques[material.technique];
  52943. if (!technique) {
  52944. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  52945. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  52946. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  52947. onSuccess(defaultMaterial);
  52948. return;
  52949. }
  52950. var program = gltfRuntime.programs[technique.program];
  52951. var states = technique.states;
  52952. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  52953. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  52954. var newVertexShader = "";
  52955. var newPixelShader = "";
  52956. var vertexTokenizer = new Tokenizer(vertexShader);
  52957. var pixelTokenizer = new Tokenizer(pixelShader);
  52958. var unTreatedUniforms = {};
  52959. var uniforms = [];
  52960. var attributes = [];
  52961. var samplers = [];
  52962. // Fill uniform, sampler2D and attributes
  52963. for (var unif in technique.uniforms) {
  52964. var uniform = technique.uniforms[unif];
  52965. var uniformParameter = technique.parameters[uniform];
  52966. unTreatedUniforms[unif] = uniformParameter;
  52967. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  52968. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  52969. if (transformIndex !== -1) {
  52970. uniforms.push(babylonTransforms[transformIndex]);
  52971. delete unTreatedUniforms[unif];
  52972. }
  52973. else {
  52974. uniforms.push(unif);
  52975. }
  52976. }
  52977. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  52978. samplers.push(unif);
  52979. }
  52980. else {
  52981. uniforms.push(unif);
  52982. }
  52983. }
  52984. for (var attr in technique.attributes) {
  52985. var attribute = technique.attributes[attr];
  52986. var attributeParameter = technique.parameters[attribute];
  52987. if (attributeParameter.semantic) {
  52988. attributes.push(getAttribute(attributeParameter));
  52989. }
  52990. }
  52991. // Configure vertex shader
  52992. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  52993. var tokenType = vertexTokenizer.currentToken;
  52994. if (tokenType !== ETokenType.IDENTIFIER) {
  52995. newVertexShader += vertexTokenizer.currentString;
  52996. continue;
  52997. }
  52998. var foundAttribute = false;
  52999. for (var attr in technique.attributes) {
  53000. var attribute = technique.attributes[attr];
  53001. var attributeParameter = technique.parameters[attribute];
  53002. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  53003. newVertexShader += getAttribute(attributeParameter);
  53004. foundAttribute = true;
  53005. break;
  53006. }
  53007. }
  53008. if (foundAttribute) {
  53009. continue;
  53010. }
  53011. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  53012. }
  53013. // Configure pixel shader
  53014. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  53015. var tokenType = pixelTokenizer.currentToken;
  53016. if (tokenType !== ETokenType.IDENTIFIER) {
  53017. newPixelShader += pixelTokenizer.currentString;
  53018. continue;
  53019. }
  53020. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  53021. }
  53022. // Create shader material
  53023. var shaderPath = {
  53024. vertex: program.vertexShader + id,
  53025. fragment: program.fragmentShader + id
  53026. };
  53027. var options = {
  53028. attributes: attributes,
  53029. uniforms: uniforms,
  53030. samplers: samplers,
  53031. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  53032. };
  53033. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  53034. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  53035. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  53036. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  53037. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  53038. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  53039. if (states && states.functions) {
  53040. var functions = states.functions;
  53041. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  53042. shaderMaterial.backFaceCulling = false;
  53043. }
  53044. var blendFunc = functions.blendFuncSeparate;
  53045. if (blendFunc) {
  53046. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  53047. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  53048. }
  53049. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  53050. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  53051. }
  53052. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  53053. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  53054. }
  53055. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  53056. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  53057. }
  53058. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  53059. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  53060. }
  53061. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  53062. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  53063. }
  53064. }
  53065. }
  53066. };
  53067. return GLTFLoaderBase;
  53068. }());
  53069. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  53070. /**
  53071. * glTF V1 Loader
  53072. */
  53073. var GLTFLoader = (function () {
  53074. function GLTFLoader() {
  53075. }
  53076. GLTFLoader.RegisterExtension = function (extension) {
  53077. if (GLTFLoader.Extensions[extension.name]) {
  53078. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  53079. return;
  53080. }
  53081. GLTFLoader.Extensions[extension.name] = extension;
  53082. };
  53083. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53084. var _this = this;
  53085. scene.useRightHandedSystem = true;
  53086. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  53087. gltfRuntime.importOnlyMeshes = true;
  53088. if (meshesNames === "") {
  53089. gltfRuntime.importMeshesNames = [];
  53090. }
  53091. else if (typeof meshesNames === "string") {
  53092. gltfRuntime.importMeshesNames = [meshesNames];
  53093. }
  53094. else if (meshesNames && !(meshesNames instanceof Array)) {
  53095. gltfRuntime.importMeshesNames = [meshesNames];
  53096. }
  53097. else {
  53098. gltfRuntime.importMeshesNames = [];
  53099. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  53100. }
  53101. // Create nodes
  53102. _this._createNodes(gltfRuntime);
  53103. var meshes = [];
  53104. var skeletons = [];
  53105. // Fill arrays of meshes and skeletons
  53106. for (var nde in gltfRuntime.nodes) {
  53107. var node = gltfRuntime.nodes[nde];
  53108. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  53109. meshes.push(node.babylonNode);
  53110. }
  53111. }
  53112. for (var skl in gltfRuntime.skins) {
  53113. var skin = gltfRuntime.skins[skl];
  53114. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  53115. skeletons.push(skin.babylonSkeleton);
  53116. }
  53117. }
  53118. // Load buffers, shaders, materials, etc.
  53119. _this._loadBuffersAsync(gltfRuntime, function () {
  53120. _this._loadShadersAsync(gltfRuntime, function () {
  53121. importMaterials(gltfRuntime);
  53122. postLoad(gltfRuntime);
  53123. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  53124. onSuccess(meshes, null, skeletons);
  53125. }
  53126. });
  53127. }, onProgress);
  53128. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  53129. onSuccess(meshes, null, skeletons);
  53130. }
  53131. }, onError);
  53132. return true;
  53133. };
  53134. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  53135. var _this = this;
  53136. scene.useRightHandedSystem = true;
  53137. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  53138. // Load runtime extensios
  53139. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  53140. // Create nodes
  53141. _this._createNodes(gltfRuntime);
  53142. // Load buffers, shaders, materials, etc.
  53143. _this._loadBuffersAsync(gltfRuntime, function () {
  53144. _this._loadShadersAsync(gltfRuntime, function () {
  53145. importMaterials(gltfRuntime);
  53146. postLoad(gltfRuntime);
  53147. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  53148. onSuccess();
  53149. }
  53150. });
  53151. });
  53152. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  53153. onSuccess();
  53154. }
  53155. }, onError);
  53156. }, onError);
  53157. };
  53158. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  53159. var hasShaders = false;
  53160. var processShader = function (sha, shader) {
  53161. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  53162. gltfRuntime.loadedShaderCount++;
  53163. if (shaderString) {
  53164. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  53165. }
  53166. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  53167. onload();
  53168. }
  53169. }, function () {
  53170. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  53171. });
  53172. };
  53173. for (var sha in gltfRuntime.shaders) {
  53174. hasShaders = true;
  53175. var shader = gltfRuntime.shaders[sha];
  53176. if (shader) {
  53177. processShader.bind(this, sha, shader)();
  53178. }
  53179. else {
  53180. BABYLON.Tools.Error("No shader named: " + sha);
  53181. }
  53182. }
  53183. if (!hasShaders) {
  53184. onload();
  53185. }
  53186. };
  53187. ;
  53188. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  53189. var hasBuffers = false;
  53190. var processBuffer = function (buf, buffer) {
  53191. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  53192. gltfRuntime.loadedBufferCount++;
  53193. if (bufferView) {
  53194. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  53195. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  53196. }
  53197. gltfRuntime.loadedBufferViews[buf] = bufferView;
  53198. }
  53199. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  53200. onLoad();
  53201. }
  53202. }, function () {
  53203. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  53204. });
  53205. };
  53206. for (var buf in gltfRuntime.buffers) {
  53207. hasBuffers = true;
  53208. var buffer = gltfRuntime.buffers[buf];
  53209. if (buffer) {
  53210. processBuffer.bind(this, buf, buffer)();
  53211. }
  53212. else {
  53213. BABYLON.Tools.Error("No buffer named: " + buf);
  53214. }
  53215. }
  53216. if (!hasBuffers) {
  53217. onLoad();
  53218. }
  53219. };
  53220. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  53221. var currentScene = gltfRuntime.currentScene;
  53222. if (currentScene) {
  53223. // Only one scene even if multiple scenes are defined
  53224. for (var i = 0; i < currentScene.nodes.length; i++) {
  53225. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  53226. }
  53227. }
  53228. else {
  53229. // Load all scenes
  53230. for (var thing in gltfRuntime.scenes) {
  53231. currentScene = gltfRuntime.scenes[thing];
  53232. for (var i = 0; i < currentScene.nodes.length; i++) {
  53233. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  53234. }
  53235. }
  53236. }
  53237. };
  53238. GLTFLoader.Extensions = {};
  53239. return GLTFLoader;
  53240. }());
  53241. GLTF1.GLTFLoader = GLTFLoader;
  53242. ;
  53243. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  53244. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53245. })(BABYLON || (BABYLON = {}));
  53246. //# sourceMappingURL=babylon.glTFLoader.js.map
  53247. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53248. var BABYLON;
  53249. (function (BABYLON) {
  53250. var GLTF1;
  53251. (function (GLTF1) {
  53252. /**
  53253. * Utils functions for GLTF
  53254. */
  53255. var GLTFUtils = (function () {
  53256. function GLTFUtils() {
  53257. }
  53258. /**
  53259. * Sets the given "parameter" matrix
  53260. * @param scene: the {BABYLON.Scene} object
  53261. * @param source: the source node where to pick the matrix
  53262. * @param parameter: the GLTF technique parameter
  53263. * @param uniformName: the name of the shader's uniform
  53264. * @param shaderMaterial: the shader material
  53265. */
  53266. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  53267. var mat = null;
  53268. if (parameter.semantic === "MODEL") {
  53269. mat = source.getWorldMatrix();
  53270. }
  53271. else if (parameter.semantic === "PROJECTION") {
  53272. mat = scene.getProjectionMatrix();
  53273. }
  53274. else if (parameter.semantic === "VIEW") {
  53275. mat = scene.getViewMatrix();
  53276. }
  53277. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  53278. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  53279. }
  53280. else if (parameter.semantic === "MODELVIEW") {
  53281. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  53282. }
  53283. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  53284. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  53285. }
  53286. else if (parameter.semantic === "MODELINVERSE") {
  53287. mat = source.getWorldMatrix().invert();
  53288. }
  53289. else if (parameter.semantic === "VIEWINVERSE") {
  53290. mat = scene.getViewMatrix().invert();
  53291. }
  53292. else if (parameter.semantic === "PROJECTIONINVERSE") {
  53293. mat = scene.getProjectionMatrix().invert();
  53294. }
  53295. else if (parameter.semantic === "MODELVIEWINVERSE") {
  53296. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  53297. }
  53298. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  53299. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  53300. }
  53301. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  53302. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  53303. }
  53304. else {
  53305. debugger;
  53306. }
  53307. switch (parameter.type) {
  53308. case GLTF1.EParameterType.FLOAT_MAT2:
  53309. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  53310. break;
  53311. case GLTF1.EParameterType.FLOAT_MAT3:
  53312. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  53313. break;
  53314. case GLTF1.EParameterType.FLOAT_MAT4:
  53315. shaderMaterial.setMatrix(uniformName, mat);
  53316. break;
  53317. default: break;
  53318. }
  53319. };
  53320. /**
  53321. * Sets the given "parameter" matrix
  53322. * @param shaderMaterial: the shader material
  53323. * @param uniform: the name of the shader's uniform
  53324. * @param value: the value of the uniform
  53325. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  53326. */
  53327. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  53328. switch (type) {
  53329. case GLTF1.EParameterType.FLOAT:
  53330. shaderMaterial.setFloat(uniform, value);
  53331. return true;
  53332. case GLTF1.EParameterType.FLOAT_VEC2:
  53333. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  53334. return true;
  53335. case GLTF1.EParameterType.FLOAT_VEC3:
  53336. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  53337. return true;
  53338. case GLTF1.EParameterType.FLOAT_VEC4:
  53339. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  53340. return true;
  53341. default: return false;
  53342. }
  53343. };
  53344. /**
  53345. * If the uri is a base64 string
  53346. * @param uri: the uri to test
  53347. */
  53348. GLTFUtils.IsBase64 = function (uri) {
  53349. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  53350. };
  53351. /**
  53352. * Decode the base64 uri
  53353. * @param uri: the uri to decode
  53354. */
  53355. GLTFUtils.DecodeBase64 = function (uri) {
  53356. var decodedString = atob(uri.split(",")[1]);
  53357. var bufferLength = decodedString.length;
  53358. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  53359. for (var i = 0; i < bufferLength; i++) {
  53360. bufferView[i] = decodedString.charCodeAt(i);
  53361. }
  53362. return bufferView.buffer;
  53363. };
  53364. /**
  53365. * Returns the wrap mode of the texture
  53366. * @param mode: the mode value
  53367. */
  53368. GLTFUtils.GetWrapMode = function (mode) {
  53369. switch (mode) {
  53370. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  53371. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  53372. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  53373. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  53374. }
  53375. };
  53376. /**
  53377. * Returns the byte stride giving an accessor
  53378. * @param accessor: the GLTF accessor objet
  53379. */
  53380. GLTFUtils.GetByteStrideFromType = function (accessor) {
  53381. // Needs this function since "byteStride" isn't requiered in glTF format
  53382. var type = accessor.type;
  53383. switch (type) {
  53384. case "VEC2": return 2;
  53385. case "VEC3": return 3;
  53386. case "VEC4": return 4;
  53387. case "MAT2": return 4;
  53388. case "MAT3": return 9;
  53389. case "MAT4": return 16;
  53390. default: return 1;
  53391. }
  53392. };
  53393. /**
  53394. * Returns the texture filter mode giving a mode value
  53395. * @param mode: the filter mode value
  53396. */
  53397. GLTFUtils.GetTextureFilterMode = function (mode) {
  53398. switch (mode) {
  53399. case GLTF1.ETextureFilterType.LINEAR:
  53400. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  53401. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  53402. case GLTF1.ETextureFilterType.NEAREST:
  53403. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  53404. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  53405. }
  53406. };
  53407. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  53408. var byteOffset = bufferView.byteOffset + byteOffset;
  53409. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  53410. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  53411. throw new Error("Buffer access is out of range");
  53412. }
  53413. var buffer = loadedBufferView.buffer;
  53414. byteOffset += loadedBufferView.byteOffset;
  53415. switch (componentType) {
  53416. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  53417. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  53418. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  53419. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  53420. default: return new Float32Array(buffer, byteOffset, byteLength);
  53421. }
  53422. };
  53423. /**
  53424. * Returns a buffer from its accessor
  53425. * @param gltfRuntime: the GLTF runtime
  53426. * @param accessor: the GLTF accessor
  53427. */
  53428. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  53429. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  53430. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  53431. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  53432. };
  53433. /**
  53434. * Decodes a buffer view into a string
  53435. * @param view: the buffer view
  53436. */
  53437. GLTFUtils.DecodeBufferToText = function (view) {
  53438. var result = "";
  53439. var length = view.byteLength;
  53440. for (var i = 0; i < length; ++i) {
  53441. result += String.fromCharCode(view[i]);
  53442. }
  53443. return result;
  53444. };
  53445. /**
  53446. * Returns the default material of gltf. Related to
  53447. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  53448. * @param scene: the Babylon.js scene
  53449. */
  53450. GLTFUtils.GetDefaultMaterial = function (scene) {
  53451. if (!GLTFUtils._DefaultMaterial) {
  53452. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  53453. "precision highp float;",
  53454. "",
  53455. "uniform mat4 worldView;",
  53456. "uniform mat4 projection;",
  53457. "",
  53458. "attribute vec3 position;",
  53459. "",
  53460. "void main(void)",
  53461. "{",
  53462. " gl_Position = projection * worldView * vec4(position, 1.0);",
  53463. "}"
  53464. ].join("\n");
  53465. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  53466. "precision highp float;",
  53467. "",
  53468. "uniform vec4 u_emission;",
  53469. "",
  53470. "void main(void)",
  53471. "{",
  53472. " gl_FragColor = u_emission;",
  53473. "}"
  53474. ].join("\n");
  53475. var shaderPath = {
  53476. vertex: "GLTFDefaultMaterial",
  53477. fragment: "GLTFDefaultMaterial"
  53478. };
  53479. var options = {
  53480. attributes: ["position"],
  53481. uniforms: ["worldView", "projection", "u_emission"],
  53482. samplers: [],
  53483. needAlphaBlending: false
  53484. };
  53485. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  53486. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  53487. }
  53488. return GLTFUtils._DefaultMaterial;
  53489. };
  53490. // The GLTF default material
  53491. GLTFUtils._DefaultMaterial = null;
  53492. return GLTFUtils;
  53493. }());
  53494. GLTF1.GLTFUtils = GLTFUtils;
  53495. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53496. })(BABYLON || (BABYLON = {}));
  53497. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  53498. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53499. var BABYLON;
  53500. (function (BABYLON) {
  53501. var GLTF1;
  53502. (function (GLTF1) {
  53503. var GLTFLoaderExtension = (function () {
  53504. function GLTFLoaderExtension(name) {
  53505. this._name = name;
  53506. }
  53507. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  53508. get: function () {
  53509. return this._name;
  53510. },
  53511. enumerable: true,
  53512. configurable: true
  53513. });
  53514. /**
  53515. * Defines an override for loading the runtime
  53516. * Return true to stop further extensions from loading the runtime
  53517. */
  53518. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53519. return false;
  53520. };
  53521. /**
  53522. * Defines an onverride for creating gltf runtime
  53523. * Return true to stop further extensions from creating the runtime
  53524. */
  53525. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53526. return false;
  53527. };
  53528. /**
  53529. * Defines an override for loading buffers
  53530. * Return true to stop further extensions from loading this buffer
  53531. */
  53532. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  53533. return false;
  53534. };
  53535. /**
  53536. * Defines an override for loading texture buffers
  53537. * Return true to stop further extensions from loading this texture data
  53538. */
  53539. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53540. return false;
  53541. };
  53542. /**
  53543. * Defines an override for creating textures
  53544. * Return true to stop further extensions from loading this texture
  53545. */
  53546. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  53547. return false;
  53548. };
  53549. /**
  53550. * Defines an override for loading shader strings
  53551. * Return true to stop further extensions from loading this shader data
  53552. */
  53553. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53554. return false;
  53555. };
  53556. /**
  53557. * Defines an override for loading materials
  53558. * Return true to stop further extensions from loading this material
  53559. */
  53560. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53561. return false;
  53562. };
  53563. // ---------
  53564. // Utilities
  53565. // ---------
  53566. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53567. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53568. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  53569. }, function () {
  53570. setTimeout(function () {
  53571. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  53572. });
  53573. });
  53574. };
  53575. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53576. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53577. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  53578. }, function () {
  53579. setTimeout(function () {
  53580. onSuccess();
  53581. });
  53582. });
  53583. };
  53584. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  53585. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53586. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  53587. }, function () {
  53588. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  53589. });
  53590. };
  53591. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  53592. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  53593. };
  53594. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53595. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53596. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  53597. }, function () {
  53598. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  53599. });
  53600. };
  53601. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53602. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53603. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  53604. }, function () {
  53605. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  53606. });
  53607. };
  53608. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53609. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53610. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  53611. }, function () {
  53612. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  53613. });
  53614. };
  53615. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  53616. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53617. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  53618. }, function () {
  53619. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  53620. });
  53621. };
  53622. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  53623. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  53624. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  53625. if (func(loaderExtension)) {
  53626. return;
  53627. }
  53628. }
  53629. defaultFunc();
  53630. };
  53631. return GLTFLoaderExtension;
  53632. }());
  53633. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  53634. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53635. })(BABYLON || (BABYLON = {}));
  53636. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  53637. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53638. var BABYLON;
  53639. (function (BABYLON) {
  53640. var GLTF1;
  53641. (function (GLTF1) {
  53642. var BinaryExtensionBufferName = "binary_glTF";
  53643. var EContentFormat;
  53644. (function (EContentFormat) {
  53645. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  53646. })(EContentFormat || (EContentFormat = {}));
  53647. ;
  53648. ;
  53649. ;
  53650. var GLTFBinaryExtension = (function (_super) {
  53651. __extends(GLTFBinaryExtension, _super);
  53652. function GLTFBinaryExtension() {
  53653. return _super.call(this, "KHR_binary_glTF") || this;
  53654. }
  53655. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53656. var extensionsUsed = data.json.extensionsUsed;
  53657. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  53658. return false;
  53659. }
  53660. this._bin = data.bin;
  53661. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  53662. return true;
  53663. };
  53664. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53665. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  53666. return false;
  53667. }
  53668. if (id !== BinaryExtensionBufferName) {
  53669. return false;
  53670. }
  53671. onSuccess(this._bin);
  53672. return true;
  53673. };
  53674. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53675. var texture = gltfRuntime.textures[id];
  53676. var source = gltfRuntime.images[texture.source];
  53677. if (!source.extensions || !(this.name in source.extensions)) {
  53678. return false;
  53679. }
  53680. var sourceExt = source.extensions[this.name];
  53681. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  53682. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  53683. onSuccess(buffer);
  53684. return true;
  53685. };
  53686. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53687. var shader = gltfRuntime.shaders[id];
  53688. if (!shader.extensions || !(this.name in shader.extensions)) {
  53689. return false;
  53690. }
  53691. var binaryExtensionShader = shader.extensions[this.name];
  53692. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  53693. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  53694. setTimeout(function () {
  53695. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  53696. onSuccess(shaderString);
  53697. });
  53698. return true;
  53699. };
  53700. return GLTFBinaryExtension;
  53701. }(GLTF1.GLTFLoaderExtension));
  53702. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  53703. var BinaryReader = (function () {
  53704. function BinaryReader(arrayBuffer) {
  53705. this._arrayBuffer = arrayBuffer;
  53706. this._dataView = new DataView(arrayBuffer);
  53707. this._byteOffset = 0;
  53708. }
  53709. BinaryReader.prototype.getUint32 = function () {
  53710. var value = this._dataView.getUint32(this._byteOffset, true);
  53711. this._byteOffset += 4;
  53712. return value;
  53713. };
  53714. BinaryReader.prototype.getUint8Array = function (length) {
  53715. if (!length) {
  53716. length = this._arrayBuffer.byteLength - this._byteOffset;
  53717. }
  53718. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  53719. this._byteOffset += length;
  53720. return value;
  53721. };
  53722. return BinaryReader;
  53723. }());
  53724. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  53725. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53726. })(BABYLON || (BABYLON = {}));
  53727. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  53728. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53729. var BABYLON;
  53730. (function (BABYLON) {
  53731. var GLTF1;
  53732. (function (GLTF1) {
  53733. ;
  53734. ;
  53735. ;
  53736. var GLTFMaterialsCommonExtension = (function (_super) {
  53737. __extends(GLTFMaterialsCommonExtension, _super);
  53738. function GLTFMaterialsCommonExtension() {
  53739. return _super.call(this, "KHR_materials_common") || this;
  53740. }
  53741. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53742. if (!gltfRuntime.extensions)
  53743. return false;
  53744. var extension = gltfRuntime.extensions[this.name];
  53745. if (!extension)
  53746. return false;
  53747. // Create lights
  53748. var lights = extension.lights;
  53749. if (lights) {
  53750. for (var thing in lights) {
  53751. var light = lights[thing];
  53752. switch (light.type) {
  53753. case "ambient":
  53754. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  53755. var ambient = light.ambient;
  53756. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  53757. break;
  53758. case "point":
  53759. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  53760. var point = light.point;
  53761. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  53762. break;
  53763. case "directional":
  53764. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  53765. var directional = light.directional;
  53766. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  53767. break;
  53768. case "spot":
  53769. var spot = light.spot;
  53770. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), light.spot.fallOffAngle || Math.PI, light.spot.fallOffExponent || 0.0, gltfRuntime.scene);
  53771. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  53772. break;
  53773. default:
  53774. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  53775. break;
  53776. }
  53777. }
  53778. }
  53779. return false;
  53780. };
  53781. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53782. var material = gltfRuntime.materials[id];
  53783. if (!material || !material.extensions)
  53784. return false;
  53785. var extension = material.extensions[this.name];
  53786. if (!extension)
  53787. return false;
  53788. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  53789. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  53790. if (extension.technique === "CONSTANT") {
  53791. standardMaterial.disableLighting = true;
  53792. }
  53793. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  53794. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  53795. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  53796. // Ambient
  53797. if (typeof extension.values.ambient === "string") {
  53798. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  53799. }
  53800. else {
  53801. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  53802. }
  53803. // Diffuse
  53804. if (typeof extension.values.diffuse === "string") {
  53805. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  53806. }
  53807. else {
  53808. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  53809. }
  53810. // Emission
  53811. if (typeof extension.values.emission === "string") {
  53812. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  53813. }
  53814. else {
  53815. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  53816. }
  53817. // Specular
  53818. if (typeof extension.values.specular === "string") {
  53819. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  53820. }
  53821. else {
  53822. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  53823. }
  53824. return true;
  53825. };
  53826. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  53827. // Create buffer from texture url
  53828. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  53829. // Create texture from buffer
  53830. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  53831. }, onError);
  53832. };
  53833. return GLTFMaterialsCommonExtension;
  53834. }(GLTF1.GLTFLoaderExtension));
  53835. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  53836. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  53837. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53838. })(BABYLON || (BABYLON = {}));
  53839. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  53840. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53841. var BABYLON;
  53842. (function (BABYLON) {
  53843. var GLTF2;
  53844. (function (GLTF2) {
  53845. /**
  53846. * Enums
  53847. */
  53848. var EComponentType;
  53849. (function (EComponentType) {
  53850. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  53851. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  53852. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  53853. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  53854. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  53855. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  53856. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  53857. var EMeshPrimitiveMode;
  53858. (function (EMeshPrimitiveMode) {
  53859. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  53860. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  53861. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  53862. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  53863. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  53864. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  53865. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  53866. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  53867. var ETextureMagFilter;
  53868. (function (ETextureMagFilter) {
  53869. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  53870. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  53871. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  53872. var ETextureMinFilter;
  53873. (function (ETextureMinFilter) {
  53874. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  53875. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  53876. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  53877. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  53878. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  53879. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  53880. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  53881. var ETextureWrapMode;
  53882. (function (ETextureWrapMode) {
  53883. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  53884. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  53885. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  53886. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  53887. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  53888. })(BABYLON || (BABYLON = {}));
  53889. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  53890. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53891. var BABYLON;
  53892. (function (BABYLON) {
  53893. var GLTF2;
  53894. (function (GLTF2) {
  53895. var GLTFLoader = (function () {
  53896. function GLTFLoader(parent) {
  53897. this._renderReady = false;
  53898. this._disposed = false;
  53899. this._objectURLs = new Array();
  53900. this._blockPendingTracking = false;
  53901. // Observable with boolean indicating success or error.
  53902. this._renderReadyObservable = new BABYLON.Observable();
  53903. // Count of pending work that needs to complete before the asset is rendered.
  53904. this._renderPendingCount = 0;
  53905. // Count of pending work that needs to complete before the loader is cleared.
  53906. this._loaderPendingCount = 0;
  53907. this._parent = parent;
  53908. }
  53909. GLTFLoader.RegisterExtension = function (extension) {
  53910. if (GLTFLoader.Extensions[extension.name]) {
  53911. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  53912. return;
  53913. }
  53914. GLTFLoader.Extensions[extension.name] = extension;
  53915. // Keep the order of registration so that extensions registered first are called first.
  53916. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  53917. };
  53918. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  53919. get: function () {
  53920. return this._gltf;
  53921. },
  53922. enumerable: true,
  53923. configurable: true
  53924. });
  53925. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  53926. get: function () {
  53927. return this._babylonScene;
  53928. },
  53929. enumerable: true,
  53930. configurable: true
  53931. });
  53932. GLTFLoader.prototype.executeWhenRenderReady = function (func) {
  53933. if (this._renderReady) {
  53934. func();
  53935. }
  53936. else {
  53937. this._renderReadyObservable.add(func);
  53938. }
  53939. };
  53940. GLTFLoader.prototype.dispose = function () {
  53941. if (this._disposed) {
  53942. return;
  53943. }
  53944. this._disposed = true;
  53945. // Revoke object urls created during load
  53946. this._objectURLs.forEach(function (url) { return URL.revokeObjectURL(url); });
  53947. this._objectURLs.length = 0;
  53948. this._gltf = undefined;
  53949. this._babylonScene = undefined;
  53950. this._rootUrl = undefined;
  53951. this._defaultMaterial = undefined;
  53952. this._successCallback = undefined;
  53953. this._errorCallback = undefined;
  53954. this._renderReady = false;
  53955. this._renderReadyObservable.clear();
  53956. this._renderPendingCount = 0;
  53957. this._loaderPendingCount = 0;
  53958. };
  53959. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53960. var _this = this;
  53961. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  53962. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  53963. }, onProgress, onError);
  53964. };
  53965. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  53966. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  53967. };
  53968. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53969. this._loadData(data);
  53970. this._babylonScene = scene;
  53971. this._rootUrl = rootUrl;
  53972. this._successCallback = onSuccess;
  53973. this._progressCallback = onProgress;
  53974. this._errorCallback = onError;
  53975. this.addPendingData(this);
  53976. this._loadScene(nodeNames);
  53977. this._loadAnimations();
  53978. this.removePendingData(this);
  53979. };
  53980. GLTFLoader.prototype._onError = function (message) {
  53981. this._errorCallback(message);
  53982. this.dispose();
  53983. };
  53984. GLTFLoader.prototype._onProgress = function (event) {
  53985. this._progressCallback(event);
  53986. };
  53987. GLTFLoader.prototype._onRenderReady = function () {
  53988. switch (this._parent.coordinateSystemMode) {
  53989. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  53990. if (!this._babylonScene.useRightHandedSystem) {
  53991. this._addRightHandToLeftHandRootTransform();
  53992. }
  53993. break;
  53994. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  53995. // do nothing
  53996. break;
  53997. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  53998. this._babylonScene.useRightHandedSystem = true;
  53999. break;
  54000. default:
  54001. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  54002. break;
  54003. }
  54004. this._showMeshes();
  54005. this._startAnimations();
  54006. this._successCallback();
  54007. this._renderReadyObservable.notifyObservers(this);
  54008. };
  54009. GLTFLoader.prototype._onLoaderComplete = function () {
  54010. if (this._parent.onComplete) {
  54011. this._parent.onComplete();
  54012. }
  54013. };
  54014. GLTFLoader.prototype._onLoaderFirstLODComplete = function () {
  54015. if (this._parent.onFirstLODComplete) {
  54016. this._parent.onFirstLODComplete();
  54017. }
  54018. };
  54019. GLTFLoader.prototype._loadData = function (data) {
  54020. this._gltf = data.json;
  54021. var binaryBuffer;
  54022. var buffers = this._gltf.buffers;
  54023. if (buffers.length > 0 && buffers[0].uri === undefined) {
  54024. binaryBuffer = buffers[0];
  54025. }
  54026. if (data.bin) {
  54027. if (binaryBuffer) {
  54028. if (binaryBuffer.byteLength != data.bin.byteLength) {
  54029. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  54030. }
  54031. }
  54032. else {
  54033. BABYLON.Tools.Warn("Unexpected BIN chunk");
  54034. }
  54035. binaryBuffer.loadedData = data.bin;
  54036. }
  54037. };
  54038. GLTFLoader.prototype._addRightHandToLeftHandRootTransform = function () {
  54039. var rootMesh = new BABYLON.Mesh("root", this._babylonScene);
  54040. rootMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  54041. rootMesh.rotation.y = Math.PI;
  54042. var nodes = this._gltf.nodes;
  54043. for (var i = 0; i < nodes.length; i++) {
  54044. var mesh = nodes[i].babylonMesh;
  54045. if (mesh && !mesh.parent) {
  54046. mesh.parent = rootMesh;
  54047. }
  54048. }
  54049. };
  54050. GLTFLoader.prototype._getMeshes = function () {
  54051. var meshes = [];
  54052. var nodes = this._gltf.nodes;
  54053. if (nodes) {
  54054. nodes.forEach(function (node) {
  54055. if (node.babylonMesh) {
  54056. meshes.push(node.babylonMesh);
  54057. }
  54058. });
  54059. }
  54060. return meshes;
  54061. };
  54062. GLTFLoader.prototype._getSkeletons = function () {
  54063. var skeletons = [];
  54064. var skins = this._gltf.skins;
  54065. if (skins) {
  54066. skins.forEach(function (skin) {
  54067. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  54068. skeletons.push(skin.babylonSkeleton);
  54069. }
  54070. });
  54071. }
  54072. return skeletons;
  54073. };
  54074. GLTFLoader.prototype._getAnimationTargets = function () {
  54075. var targets = [];
  54076. var animations = this._gltf.animations;
  54077. if (animations) {
  54078. animations.forEach(function (animation) {
  54079. targets.push.apply(targets, animation.targets);
  54080. });
  54081. }
  54082. return targets;
  54083. };
  54084. GLTFLoader.prototype._showMeshes = function () {
  54085. this._getMeshes().forEach(function (mesh) { return mesh.isVisible = true; });
  54086. };
  54087. GLTFLoader.prototype._startAnimations = function () {
  54088. var _this = this;
  54089. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  54090. };
  54091. GLTFLoader.prototype._loadScene = function (nodeNames) {
  54092. var _this = this;
  54093. var scene = this._gltf.scenes[this._gltf.scene || 0];
  54094. var nodeIndices = scene.nodes;
  54095. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  54096. node.index = index;
  54097. node.parent = parentNode;
  54098. return true;
  54099. });
  54100. var materials = this._gltf.materials;
  54101. if (materials) {
  54102. materials.forEach(function (material, index) { return material.index = index; });
  54103. }
  54104. if (nodeNames) {
  54105. if (!(nodeNames instanceof Array)) {
  54106. nodeNames = [nodeNames];
  54107. }
  54108. var filteredNodeIndices = new Array();
  54109. this._traverseNodes(nodeIndices, function (node) {
  54110. if (nodeNames.indexOf(node.name) === -1) {
  54111. return true;
  54112. }
  54113. filteredNodeIndices.push(node.index);
  54114. return false;
  54115. });
  54116. nodeIndices = filteredNodeIndices;
  54117. }
  54118. this._traverseNodes(nodeIndices, function (node) { return _this._loadSkin(node); });
  54119. this._traverseNodes(nodeIndices, function (node) { return _this._loadMesh(node); });
  54120. };
  54121. GLTFLoader.prototype._loadSkin = function (node) {
  54122. var _this = this;
  54123. if (node.skin !== undefined) {
  54124. var skin = this._gltf.skins[node.skin];
  54125. var skeletonId = "skeleton" + node.skin;
  54126. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  54127. skin.index = node.skin;
  54128. for (var i = 0; i < skin.joints.length; i++) {
  54129. this._createBone(this._gltf.nodes[skin.joints[i]], skin);
  54130. }
  54131. if (skin.skeleton === undefined) {
  54132. // TODO: handle when skeleton is not defined
  54133. throw new Error("Not implemented");
  54134. }
  54135. if (skin.inverseBindMatrices === undefined) {
  54136. // TODO: handle when inverse bind matrices are not defined
  54137. throw new Error("Not implemented");
  54138. }
  54139. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  54140. this._loadAccessorAsync(accessor, function (data) {
  54141. _this._traverseNode(skin.skeleton, function (node, index, parent) { return _this._updateBone(node, parent, skin, data); });
  54142. });
  54143. }
  54144. return true;
  54145. };
  54146. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  54147. var jointIndex = skin.joints.indexOf(node.index);
  54148. if (jointIndex === -1) {
  54149. this._createBone(node, skin);
  54150. }
  54151. var babylonBone = node.babylonSkinToBones[skin.index];
  54152. // TODO: explain the math
  54153. var matrix = jointIndex === -1 ? BABYLON.Matrix.Identity() : BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  54154. matrix.invertToRef(matrix);
  54155. if (parentNode) {
  54156. babylonBone.setParent(parentNode.babylonSkinToBones[skin.index], false);
  54157. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  54158. }
  54159. babylonBone.updateMatrix(matrix);
  54160. return true;
  54161. };
  54162. GLTFLoader.prototype._createBone = function (node, skin) {
  54163. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton);
  54164. node.babylonSkinToBones = node.babylonSkinToBones || {};
  54165. node.babylonSkinToBones[skin.index] = babylonBone;
  54166. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  54167. node.babylonAnimationTargets.push(babylonBone);
  54168. return babylonBone;
  54169. };
  54170. GLTFLoader.prototype._loadMesh = function (node) {
  54171. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  54172. babylonMesh.isVisible = false;
  54173. this._loadTransform(node, babylonMesh);
  54174. if (node.mesh !== undefined) {
  54175. var mesh = this._gltf.meshes[node.mesh];
  54176. this._loadMeshData(node, mesh, babylonMesh);
  54177. }
  54178. babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  54179. node.babylonMesh = babylonMesh;
  54180. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  54181. node.babylonAnimationTargets.push(node.babylonMesh);
  54182. if (node.skin !== undefined) {
  54183. var skin = this._gltf.skins[node.skin];
  54184. babylonMesh.skeleton = skin.babylonSkeleton;
  54185. }
  54186. if (node.camera !== undefined) {
  54187. // TODO: handle cameras
  54188. }
  54189. return true;
  54190. };
  54191. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  54192. var _this = this;
  54193. babylonMesh.name = mesh.name || babylonMesh.name;
  54194. var babylonMultiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  54195. babylonMesh.material = babylonMultiMaterial;
  54196. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  54197. var vertexData = new BABYLON.VertexData();
  54198. vertexData.positions = [];
  54199. vertexData.indices = [];
  54200. var subMeshInfos = [];
  54201. var loadedPrimitives = 0;
  54202. var totalPrimitives = mesh.primitives.length;
  54203. var _loop_1 = function (i) {
  54204. var primitive = mesh.primitives[i];
  54205. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  54206. // TODO: handle other primitive modes
  54207. throw new Error("Not implemented");
  54208. }
  54209. this_1._createMorphTargets(node, mesh, primitive, babylonMesh);
  54210. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  54211. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  54212. subMeshInfos.push({
  54213. materialIndex: i,
  54214. verticesStart: vertexData.positions.length,
  54215. verticesCount: subVertexData.positions.length,
  54216. indicesStart: vertexData.indices.length,
  54217. indicesCount: subVertexData.indices.length,
  54218. loadMaterial: function () {
  54219. if (primitive.material === undefined) {
  54220. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  54221. }
  54222. else {
  54223. var material = _this._gltf.materials[primitive.material];
  54224. _this.loadMaterial(material, function (babylonMaterial, isNew) {
  54225. if (isNew && _this._parent.onMaterialLoaded) {
  54226. _this._parent.onMaterialLoaded(babylonMaterial);
  54227. }
  54228. if (_this._parent.onBeforeMaterialReadyAsync) {
  54229. _this.addLoaderPendingData(material);
  54230. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, babylonMesh, babylonMultiMaterial.subMaterials[i] != null, function () {
  54231. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  54232. _this.removeLoaderPendingData(material);
  54233. });
  54234. }
  54235. else {
  54236. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  54237. }
  54238. });
  54239. }
  54240. }
  54241. });
  54242. vertexData.merge(subVertexData);
  54243. if (++loadedPrimitives === totalPrimitives) {
  54244. geometry.setAllVerticesData(vertexData, false);
  54245. subMeshInfos.forEach(function (info) { return info.loadMaterial(); });
  54246. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  54247. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  54248. babylonMesh.subMeshes = [];
  54249. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, babylonMesh); });
  54250. }
  54251. });
  54252. };
  54253. var this_1 = this;
  54254. for (var i = 0; i < totalPrimitives; i++) {
  54255. _loop_1(i);
  54256. }
  54257. };
  54258. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  54259. var _this = this;
  54260. var attributes = primitive.attributes;
  54261. if (!attributes) {
  54262. this._onError("Primitive has no attributes");
  54263. return;
  54264. }
  54265. var vertexData = new BABYLON.VertexData();
  54266. var loadedAttributes = 0;
  54267. var totalAttributes = Object.keys(attributes).length;
  54268. var _loop_2 = function (semantic) {
  54269. accessor = this_2._gltf.accessors[attributes[semantic]];
  54270. this_2._loadAccessorAsync(accessor, function (data) {
  54271. switch (semantic) {
  54272. case "NORMAL":
  54273. vertexData.normals = data;
  54274. break;
  54275. case "POSITION":
  54276. vertexData.positions = data;
  54277. break;
  54278. case "TANGENT":
  54279. vertexData.tangents = data;
  54280. break;
  54281. case "TEXCOORD_0":
  54282. vertexData.uvs = data;
  54283. break;
  54284. case "TEXCOORD_1":
  54285. vertexData.uvs2 = data;
  54286. break;
  54287. case "JOINTS_0":
  54288. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  54289. break;
  54290. case "WEIGHTS_0":
  54291. vertexData.matricesWeights = data;
  54292. break;
  54293. case "COLOR_0":
  54294. vertexData.colors = data;
  54295. break;
  54296. default:
  54297. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  54298. break;
  54299. }
  54300. if (++loadedAttributes === totalAttributes) {
  54301. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  54302. if (indicesAccessor) {
  54303. _this._loadAccessorAsync(indicesAccessor, function (data) {
  54304. vertexData.indices = data;
  54305. onSuccess(vertexData);
  54306. });
  54307. }
  54308. else {
  54309. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  54310. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  54311. onSuccess(vertexData);
  54312. }
  54313. }
  54314. });
  54315. };
  54316. var this_2 = this, accessor;
  54317. for (var semantic in attributes) {
  54318. _loop_2(semantic);
  54319. }
  54320. };
  54321. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  54322. var targets = primitive.targets;
  54323. if (!targets) {
  54324. return;
  54325. }
  54326. if (!babylonMesh.morphTargetManager) {
  54327. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  54328. }
  54329. for (var index = 0; index < targets.length; index++) {
  54330. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  54331. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  54332. }
  54333. };
  54334. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  54335. var targets = primitive.targets;
  54336. if (!targets) {
  54337. return;
  54338. }
  54339. var _loop_3 = function () {
  54340. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  54341. attributes = targets[index];
  54342. var _loop_4 = function (semantic) {
  54343. accessor = this_3._gltf.accessors[attributes[semantic]];
  54344. this_3._loadAccessorAsync(accessor, function (data) {
  54345. if (accessor.name) {
  54346. babylonMorphTarget.name = accessor.name;
  54347. }
  54348. // glTF stores morph target information as deltas while babylon.js expects the final data.
  54349. // As a result we have to add the original data to the delta to calculate the final data.
  54350. var values = data;
  54351. switch (semantic) {
  54352. case "NORMAL":
  54353. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  54354. babylonMorphTarget.setNormals(values);
  54355. break;
  54356. case "POSITION":
  54357. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  54358. babylonMorphTarget.setPositions(values);
  54359. break;
  54360. case "TANGENT":
  54361. // Tangent data for morph targets is stored as xyz delta.
  54362. // The vertexData.tangent is stored as xyzw.
  54363. // So we need to skip every fourth vertexData.tangent.
  54364. for (var i = 0, j = 0; i < values.length; i++, j++) {
  54365. values[i] += vertexData.tangents[j];
  54366. if ((i + 1) % 3 == 0) {
  54367. j++;
  54368. }
  54369. }
  54370. babylonMorphTarget.setTangents(values);
  54371. break;
  54372. default:
  54373. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  54374. break;
  54375. }
  54376. });
  54377. };
  54378. for (var semantic in attributes) {
  54379. _loop_4(semantic);
  54380. }
  54381. };
  54382. var this_3 = this, attributes, accessor;
  54383. for (var index = 0; index < targets.length; index++) {
  54384. _loop_3();
  54385. }
  54386. };
  54387. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  54388. var position = BABYLON.Vector3.Zero();
  54389. var rotation = BABYLON.Quaternion.Identity();
  54390. var scaling = BABYLON.Vector3.One();
  54391. if (node.matrix) {
  54392. var mat = BABYLON.Matrix.FromArray(node.matrix);
  54393. mat.decompose(scaling, rotation, position);
  54394. }
  54395. else {
  54396. if (node.translation)
  54397. position = BABYLON.Vector3.FromArray(node.translation);
  54398. if (node.rotation)
  54399. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  54400. if (node.scale)
  54401. scaling = BABYLON.Vector3.FromArray(node.scale);
  54402. }
  54403. babylonMesh.position = position;
  54404. babylonMesh.rotationQuaternion = rotation;
  54405. babylonMesh.scaling = scaling;
  54406. };
  54407. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  54408. if (parentNode === void 0) { parentNode = null; }
  54409. for (var i = 0; i < indices.length; i++) {
  54410. this._traverseNode(indices[i], action, parentNode);
  54411. }
  54412. };
  54413. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  54414. if (parentNode === void 0) { parentNode = null; }
  54415. var node = this._gltf.nodes[index];
  54416. if (!action(node, index, parentNode)) {
  54417. return;
  54418. }
  54419. if (node.children) {
  54420. for (var i = 0; i < node.children.length; i++) {
  54421. this._traverseNode(node.children[i], action, node);
  54422. }
  54423. }
  54424. };
  54425. GLTFLoader.prototype._loadAnimations = function () {
  54426. var animations = this._gltf.animations;
  54427. if (!animations || animations.length === 0) {
  54428. return;
  54429. }
  54430. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  54431. var animation = animations[animationIndex];
  54432. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  54433. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  54434. }
  54435. }
  54436. };
  54437. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  54438. var channel = animation.channels[channelIndex];
  54439. var samplerIndex = channel.sampler;
  54440. var sampler = animation.samplers[samplerIndex];
  54441. var targetNode = this._gltf.nodes[channel.target.node];
  54442. if (!targetNode) {
  54443. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  54444. return;
  54445. }
  54446. var targetPath = {
  54447. "translation": "position",
  54448. "rotation": "rotationQuaternion",
  54449. "scale": "scaling",
  54450. "weights": "influence"
  54451. }[channel.target.path];
  54452. if (!targetPath) {
  54453. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  54454. return;
  54455. }
  54456. var animationType = {
  54457. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  54458. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  54459. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  54460. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  54461. }[targetPath];
  54462. var inputData;
  54463. var outputData;
  54464. var checkSuccess = function () {
  54465. if (!inputData || !outputData) {
  54466. return;
  54467. }
  54468. var outputBufferOffset = 0;
  54469. var getNextOutputValue = {
  54470. "position": function () {
  54471. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  54472. outputBufferOffset += 3;
  54473. return value;
  54474. },
  54475. "rotationQuaternion": function () {
  54476. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  54477. outputBufferOffset += 4;
  54478. return value;
  54479. },
  54480. "scaling": function () {
  54481. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  54482. outputBufferOffset += 3;
  54483. return value;
  54484. },
  54485. "influence": function () {
  54486. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  54487. var value = new Array(numTargets);
  54488. for (var i = 0; i < numTargets; i++) {
  54489. value[i] = outputData[outputBufferOffset++];
  54490. }
  54491. return value;
  54492. },
  54493. }[targetPath];
  54494. var getNextKey = {
  54495. "LINEAR": function (frameIndex) { return ({
  54496. frame: inputData[frameIndex],
  54497. value: getNextOutputValue()
  54498. }); },
  54499. "CUBICSPLINE": function (frameIndex) { return ({
  54500. frame: inputData[frameIndex],
  54501. inTangent: getNextOutputValue(),
  54502. value: getNextOutputValue(),
  54503. outTangent: getNextOutputValue()
  54504. }); },
  54505. }[sampler.interpolation];
  54506. var keys = new Array(inputData.length);
  54507. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  54508. keys[frameIndex] = getNextKey(frameIndex);
  54509. }
  54510. animation.targets = animation.targets || [];
  54511. if (targetPath === "influence") {
  54512. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  54513. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  54514. var morphTarget = morphTargetManager.getTarget(targetIndex);
  54515. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  54516. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  54517. babylonAnimation.setKeys(keys.map(function (key) { return ({
  54518. frame: key.frame,
  54519. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  54520. value: key.value[targetIndex],
  54521. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  54522. }); }));
  54523. morphTarget.animations.push(babylonAnimation);
  54524. animation.targets.push(morphTarget);
  54525. }
  54526. }
  54527. else {
  54528. var animationName = animation.name || "anim" + animationIndex;
  54529. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  54530. babylonAnimation.setKeys(keys);
  54531. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  54532. var target = targetNode.babylonAnimationTargets[i];
  54533. target.animations.push(babylonAnimation.clone());
  54534. animation.targets.push(target);
  54535. }
  54536. }
  54537. };
  54538. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  54539. inputData = data;
  54540. checkSuccess();
  54541. });
  54542. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  54543. outputData = data;
  54544. checkSuccess();
  54545. });
  54546. };
  54547. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  54548. var _this = this;
  54549. var buffer = this._gltf.buffers[index];
  54550. this.addPendingData(buffer);
  54551. if (buffer.loadedData) {
  54552. setTimeout(function () {
  54553. onSuccess(buffer.loadedData);
  54554. _this.removePendingData(buffer);
  54555. });
  54556. }
  54557. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  54558. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  54559. buffer.loadedData = new Uint8Array(data);
  54560. setTimeout(function () {
  54561. onSuccess(buffer.loadedData);
  54562. _this.removePendingData(buffer);
  54563. });
  54564. }
  54565. else if (buffer.loadedObservable) {
  54566. buffer.loadedObservable.add(function (buffer) {
  54567. onSuccess(buffer.loadedData);
  54568. _this.removePendingData(buffer);
  54569. });
  54570. }
  54571. else {
  54572. buffer.loadedObservable = new BABYLON.Observable();
  54573. buffer.loadedObservable.add(function (buffer) {
  54574. onSuccess(buffer.loadedData);
  54575. _this.removePendingData(buffer);
  54576. });
  54577. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  54578. buffer.loadedData = new Uint8Array(data);
  54579. buffer.loadedObservable.notifyObservers(buffer);
  54580. buffer.loadedObservable = null;
  54581. }, function (event) {
  54582. if (!_this._disposed) {
  54583. _this._onProgress(event);
  54584. }
  54585. }, this._babylonScene.database, true, function (request) {
  54586. if (!_this._disposed) {
  54587. _this._onError("Failed to load file '" + buffer.uri + "': " + request.status + " " + request.statusText);
  54588. _this.removePendingData(buffer);
  54589. }
  54590. });
  54591. }
  54592. };
  54593. GLTFLoader.prototype._buildInt8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54594. if (!byteStride) {
  54595. return new Int8Array(buffer, byteOffset, byteLength);
  54596. }
  54597. var sourceBuffer = new Int8Array(buffer, byteOffset);
  54598. var targetBuffer = new Int8Array(byteLength);
  54599. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  54600. return targetBuffer;
  54601. };
  54602. GLTFLoader.prototype._buildUint8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54603. if (!byteStride) {
  54604. return new Uint8Array(buffer, byteOffset, byteLength);
  54605. }
  54606. var sourceBuffer = new Uint8Array(buffer, byteOffset);
  54607. var targetBuffer = new Uint8Array(byteLength);
  54608. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  54609. return targetBuffer;
  54610. };
  54611. GLTFLoader.prototype._buildInt16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54612. if (!byteStride) {
  54613. return new Int16Array(buffer, byteOffset, byteLength);
  54614. }
  54615. var sourceBuffer = new Int16Array(buffer, byteOffset);
  54616. var targetBuffer = new Int16Array(byteLength);
  54617. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  54618. return targetBuffer;
  54619. };
  54620. GLTFLoader.prototype._buildUint16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54621. if (!byteStride) {
  54622. return new Uint16Array(buffer, byteOffset, byteLength);
  54623. }
  54624. var sourceBuffer = new Uint16Array(buffer, byteOffset);
  54625. var targetBuffer = new Uint16Array(byteLength);
  54626. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  54627. return targetBuffer;
  54628. };
  54629. GLTFLoader.prototype._buildUint32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54630. if (!byteStride) {
  54631. return new Uint32Array(buffer, byteOffset, byteLength);
  54632. }
  54633. var sourceBuffer = new Uint32Array(buffer, byteOffset);
  54634. var targetBuffer = new Uint32Array(byteLength);
  54635. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  54636. return targetBuffer;
  54637. };
  54638. GLTFLoader.prototype._buildFloat32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54639. if (!byteStride) {
  54640. return new Float32Array(buffer, byteOffset, byteLength);
  54641. }
  54642. var sourceBuffer = new Float32Array(buffer, byteOffset);
  54643. var targetBuffer = new Float32Array(byteLength);
  54644. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  54645. return targetBuffer;
  54646. };
  54647. GLTFLoader.prototype._extractInterleavedData = function (sourceBuffer, targetBuffer, bytePerComponent, stride, length) {
  54648. var tempIndex = 0;
  54649. var sourceIndex = 0;
  54650. var storageSize = bytePerComponent;
  54651. while (tempIndex < length) {
  54652. for (var cursor = 0; cursor < storageSize; cursor++) {
  54653. targetBuffer[tempIndex] = sourceBuffer[sourceIndex + cursor];
  54654. tempIndex++;
  54655. }
  54656. sourceIndex += stride;
  54657. }
  54658. };
  54659. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, bytePerComponent, componentType, onSuccess) {
  54660. var _this = this;
  54661. byteOffset += (bufferView.byteOffset || 0);
  54662. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  54663. if (byteOffset + byteLength > bufferData.byteLength) {
  54664. _this._onError("Buffer access is out of range");
  54665. return;
  54666. }
  54667. var buffer = bufferData.buffer;
  54668. byteOffset += bufferData.byteOffset;
  54669. var bufferViewData;
  54670. switch (componentType) {
  54671. case GLTF2.EComponentType.BYTE:
  54672. bufferViewData = _this._buildInt8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54673. break;
  54674. case GLTF2.EComponentType.UNSIGNED_BYTE:
  54675. bufferViewData = _this._buildUint8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54676. break;
  54677. case GLTF2.EComponentType.SHORT:
  54678. bufferViewData = _this._buildInt16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54679. break;
  54680. case GLTF2.EComponentType.UNSIGNED_SHORT:
  54681. bufferViewData = _this._buildUint16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54682. break;
  54683. case GLTF2.EComponentType.UNSIGNED_INT:
  54684. bufferViewData = _this._buildUint32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54685. break;
  54686. case GLTF2.EComponentType.FLOAT:
  54687. bufferViewData = _this._buildFloat32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54688. break;
  54689. default:
  54690. _this._onError("Invalid component type (" + componentType + ")");
  54691. return;
  54692. }
  54693. onSuccess(bufferViewData);
  54694. });
  54695. };
  54696. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  54697. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  54698. var byteOffset = accessor.byteOffset || 0;
  54699. var bytePerComponent = this._getByteStrideFromType(accessor);
  54700. var byteLength = accessor.count * bytePerComponent;
  54701. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, bytePerComponent, accessor.componentType, onSuccess);
  54702. };
  54703. GLTFLoader.prototype._getByteStrideFromType = function (accessor) {
  54704. switch (accessor.type) {
  54705. case "SCALAR": return 1;
  54706. case "VEC2": return 2;
  54707. case "VEC3": return 3;
  54708. case "VEC4": return 4;
  54709. case "MAT2": return 4;
  54710. case "MAT3": return 9;
  54711. case "MAT4": return 16;
  54712. default:
  54713. this._onError("Invalid accessor type (" + accessor.type + ")");
  54714. return 0;
  54715. }
  54716. };
  54717. Object.defineProperty(GLTFLoader.prototype, "blockPendingTracking", {
  54718. set: function (value) {
  54719. this._blockPendingTracking = value;
  54720. },
  54721. enumerable: true,
  54722. configurable: true
  54723. });
  54724. GLTFLoader.prototype.addPendingData = function (data) {
  54725. if (!this._renderReady) {
  54726. this._renderPendingCount++;
  54727. }
  54728. this.addLoaderPendingData(data);
  54729. };
  54730. GLTFLoader.prototype.removePendingData = function (data) {
  54731. if (!this._renderReady) {
  54732. if (--this._renderPendingCount === 0) {
  54733. this._renderReady = true;
  54734. this._onRenderReady();
  54735. }
  54736. }
  54737. this.removeLoaderPendingData(data);
  54738. };
  54739. GLTFLoader.prototype.addLoaderNonBlockingPendingData = function (data) {
  54740. if (!this._nonBlockingData) {
  54741. this._nonBlockingData = new Array();
  54742. }
  54743. this._nonBlockingData.push(data);
  54744. };
  54745. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  54746. if (this._blockPendingTracking) {
  54747. this.addLoaderNonBlockingPendingData(data);
  54748. return;
  54749. }
  54750. this._loaderPendingCount++;
  54751. };
  54752. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  54753. var indexInPending = this._nonBlockingData ? this._nonBlockingData.indexOf(data) : -1;
  54754. if (indexInPending !== -1) {
  54755. this._nonBlockingData.splice(indexInPending, 1);
  54756. }
  54757. else if (--this._loaderPendingCount === 0) {
  54758. this._onLoaderFirstLODComplete();
  54759. }
  54760. if ((!this._nonBlockingData || this._nonBlockingData.length === 0) && this._loaderPendingCount === 0) {
  54761. this._onLoaderComplete();
  54762. this.dispose();
  54763. }
  54764. };
  54765. GLTFLoader.prototype._getDefaultMaterial = function () {
  54766. if (!this._defaultMaterial) {
  54767. var id = "__gltf_default";
  54768. var material = this._babylonScene.getMaterialByName(id);
  54769. if (!material) {
  54770. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  54771. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  54772. material.metallic = 1;
  54773. material.roughness = 1;
  54774. }
  54775. this._defaultMaterial = material;
  54776. }
  54777. return this._defaultMaterial;
  54778. };
  54779. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  54780. var babylonMaterial = material.babylonMaterial;
  54781. // Ensure metallic workflow
  54782. babylonMaterial.metallic = 1;
  54783. babylonMaterial.roughness = 1;
  54784. var properties = material.pbrMetallicRoughness;
  54785. if (!properties) {
  54786. return;
  54787. }
  54788. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  54789. babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  54790. babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  54791. if (properties.baseColorTexture) {
  54792. babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  54793. }
  54794. if (properties.metallicRoughnessTexture) {
  54795. babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  54796. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  54797. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  54798. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  54799. }
  54800. this.loadMaterialAlphaProperties(material, properties.baseColorFactor);
  54801. };
  54802. GLTFLoader.prototype.loadMaterial = function (material, assign) {
  54803. if (material.babylonMaterial) {
  54804. assign(material.babylonMaterial, false);
  54805. return;
  54806. }
  54807. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  54808. return;
  54809. }
  54810. this.createPbrMaterial(material);
  54811. this.loadMaterialBaseProperties(material);
  54812. this._loadMaterialMetallicRoughnessProperties(material);
  54813. assign(material.babylonMaterial, true);
  54814. };
  54815. GLTFLoader.prototype.createPbrMaterial = function (material) {
  54816. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  54817. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  54818. material.babylonMaterial = babylonMaterial;
  54819. };
  54820. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  54821. var babylonMaterial = material.babylonMaterial;
  54822. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  54823. if (material.doubleSided) {
  54824. babylonMaterial.backFaceCulling = false;
  54825. babylonMaterial.twoSidedLighting = true;
  54826. }
  54827. if (material.normalTexture) {
  54828. babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  54829. babylonMaterial.invertNormalMapX = true;
  54830. babylonMaterial.invertNormalMapY = false;
  54831. if (material.normalTexture.scale !== undefined) {
  54832. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  54833. }
  54834. }
  54835. if (material.occlusionTexture) {
  54836. babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  54837. babylonMaterial.useAmbientInGrayScale = true;
  54838. if (material.occlusionTexture.strength !== undefined) {
  54839. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  54840. }
  54841. }
  54842. if (material.emissiveTexture) {
  54843. babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  54844. }
  54845. };
  54846. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material, colorFactor) {
  54847. var babylonMaterial = material.babylonMaterial;
  54848. var alphaMode = material.alphaMode || "OPAQUE";
  54849. switch (alphaMode) {
  54850. case "OPAQUE":
  54851. // default is opaque
  54852. break;
  54853. case "MASK":
  54854. case "BLEND":
  54855. if (colorFactor) {
  54856. babylonMaterial.alpha = colorFactor[3];
  54857. }
  54858. if (babylonMaterial.albedoTexture) {
  54859. babylonMaterial.albedoTexture.hasAlpha = true;
  54860. babylonMaterial.useAlphaFromAlbedoTexture = (alphaMode === "BLEND");
  54861. }
  54862. break;
  54863. default:
  54864. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  54865. break;
  54866. }
  54867. };
  54868. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  54869. var _this = this;
  54870. var texture = this._gltf.textures[textureInfo.index];
  54871. var texCoord = textureInfo.texCoord || 0;
  54872. if (!texture || texture.source === undefined) {
  54873. return null;
  54874. }
  54875. // check the cache first
  54876. var babylonTexture;
  54877. if (texture.babylonTextures) {
  54878. babylonTexture = texture.babylonTextures[texCoord];
  54879. if (!babylonTexture) {
  54880. for (var i = 0; i < texture.babylonTextures.length; i++) {
  54881. babylonTexture = texture.babylonTextures[i];
  54882. if (babylonTexture) {
  54883. babylonTexture = babylonTexture.clone();
  54884. babylonTexture.coordinatesIndex = texCoord;
  54885. break;
  54886. }
  54887. }
  54888. }
  54889. return babylonTexture;
  54890. }
  54891. var source = this._gltf.images[texture.source];
  54892. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  54893. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  54894. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  54895. this.addPendingData(texture);
  54896. babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  54897. if (!_this._disposed) {
  54898. _this.removePendingData(texture);
  54899. }
  54900. }, function () {
  54901. if (!_this._disposed) {
  54902. _this._onError("Failed to load texture '" + source.uri + "'");
  54903. _this.removePendingData(texture);
  54904. }
  54905. });
  54906. var setTextureData = function (data) {
  54907. var url = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  54908. _this._objectURLs.push(url);
  54909. babylonTexture.updateURL(url);
  54910. };
  54911. if (!source.uri) {
  54912. var bufferView = this._gltf.bufferViews[source.bufferView];
  54913. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, 1, GLTF2.EComponentType.UNSIGNED_BYTE, setTextureData);
  54914. }
  54915. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  54916. setTextureData(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri)));
  54917. }
  54918. else {
  54919. BABYLON.Tools.LoadFile(this._rootUrl + source.uri, setTextureData, function (event) {
  54920. if (!_this._disposed) {
  54921. _this._onProgress(event);
  54922. }
  54923. }, this._babylonScene.database, true, function (request) {
  54924. _this._onError("Failed to load file '" + source.uri + "': " + request.status + " " + request.statusText);
  54925. });
  54926. }
  54927. babylonTexture.coordinatesIndex = texCoord;
  54928. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  54929. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  54930. babylonTexture.name = texture.name || "texture" + textureInfo.index;
  54931. // Cache the texture
  54932. texture.babylonTextures = texture.babylonTextures || [];
  54933. texture.babylonTextures[texCoord] = babylonTexture;
  54934. if (this._parent.onTextureLoaded) {
  54935. this._parent.onTextureLoaded(babylonTexture);
  54936. }
  54937. return babylonTexture;
  54938. };
  54939. GLTFLoader.Extensions = {};
  54940. return GLTFLoader;
  54941. }());
  54942. GLTF2.GLTFLoader = GLTFLoader;
  54943. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  54944. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54945. })(BABYLON || (BABYLON = {}));
  54946. //# sourceMappingURL=babylon.glTFLoader.js.map
  54947. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  54948. var BABYLON;
  54949. (function (BABYLON) {
  54950. var GLTF2;
  54951. (function (GLTF2) {
  54952. /**
  54953. * Utils functions for GLTF
  54954. */
  54955. var GLTFUtils = (function () {
  54956. function GLTFUtils() {
  54957. }
  54958. /**
  54959. * If the uri is a base64 string
  54960. * @param uri: the uri to test
  54961. */
  54962. GLTFUtils.IsBase64 = function (uri) {
  54963. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  54964. };
  54965. /**
  54966. * Decode the base64 uri
  54967. * @param uri: the uri to decode
  54968. */
  54969. GLTFUtils.DecodeBase64 = function (uri) {
  54970. var decodedString = atob(uri.split(",")[1]);
  54971. var bufferLength = decodedString.length;
  54972. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  54973. for (var i = 0; i < bufferLength; i++) {
  54974. bufferView[i] = decodedString.charCodeAt(i);
  54975. }
  54976. return bufferView.buffer;
  54977. };
  54978. GLTFUtils.ForEach = function (view, func) {
  54979. for (var index = 0; index < view.length; index++) {
  54980. func(view[index], index);
  54981. }
  54982. };
  54983. GLTFUtils.GetTextureWrapMode = function (mode) {
  54984. // Set defaults if undefined
  54985. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  54986. switch (mode) {
  54987. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  54988. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  54989. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  54990. default:
  54991. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  54992. return BABYLON.Texture.WRAP_ADDRESSMODE;
  54993. }
  54994. };
  54995. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  54996. // Set defaults if undefined
  54997. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  54998. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST : minFilter;
  54999. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  55000. switch (minFilter) {
  55001. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  55002. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  55003. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  55004. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  55005. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  55006. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  55007. default:
  55008. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  55009. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  55010. }
  55011. }
  55012. else {
  55013. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  55014. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  55015. }
  55016. switch (minFilter) {
  55017. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  55018. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  55019. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  55020. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  55021. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  55022. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  55023. default:
  55024. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  55025. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  55026. }
  55027. }
  55028. };
  55029. /**
  55030. * Decodes a buffer view into a string
  55031. * @param view: the buffer view
  55032. */
  55033. GLTFUtils.DecodeBufferToText = function (view) {
  55034. var result = "";
  55035. var length = view.byteLength;
  55036. for (var i = 0; i < length; ++i) {
  55037. result += String.fromCharCode(view[i]);
  55038. }
  55039. return result;
  55040. };
  55041. return GLTFUtils;
  55042. }());
  55043. GLTF2.GLTFUtils = GLTFUtils;
  55044. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  55045. })(BABYLON || (BABYLON = {}));
  55046. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  55047. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  55048. var BABYLON;
  55049. (function (BABYLON) {
  55050. var GLTF2;
  55051. (function (GLTF2) {
  55052. var GLTFLoaderExtension = (function () {
  55053. function GLTFLoaderExtension() {
  55054. this.enabled = true;
  55055. }
  55056. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  55057. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  55058. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  55059. };
  55060. GLTFLoaderExtension._ApplyExtensions = function (action) {
  55061. var extensions = GLTFLoaderExtension._Extensions;
  55062. if (!extensions) {
  55063. return;
  55064. }
  55065. for (var i = 0; i < extensions.length; i++) {
  55066. var extension = extensions[i];
  55067. if (extension.enabled && action(extension)) {
  55068. return true;
  55069. }
  55070. }
  55071. return false;
  55072. };
  55073. //
  55074. // Utilities
  55075. //
  55076. GLTFLoaderExtension._Extensions = [];
  55077. return GLTFLoaderExtension;
  55078. }());
  55079. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  55080. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  55081. })(BABYLON || (BABYLON = {}));
  55082. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  55083. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  55084. var BABYLON;
  55085. (function (BABYLON) {
  55086. var GLTF2;
  55087. (function (GLTF2) {
  55088. var Extensions;
  55089. (function (Extensions) {
  55090. var MSFTLOD = (function (_super) {
  55091. __extends(MSFTLOD, _super);
  55092. function MSFTLOD() {
  55093. return _super !== null && _super.apply(this, arguments) || this;
  55094. }
  55095. Object.defineProperty(MSFTLOD.prototype, "name", {
  55096. get: function () {
  55097. return "MSFT_lod";
  55098. },
  55099. enumerable: true,
  55100. configurable: true
  55101. });
  55102. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  55103. if (!material.extensions) {
  55104. return false;
  55105. }
  55106. var properties = material.extensions[this.name];
  55107. if (!properties) {
  55108. return false;
  55109. }
  55110. // Clear out the extension so that it won't get loaded again.
  55111. material.extensions[this.name] = undefined;
  55112. // Tell the loader not to clear its state until the highest LOD is loaded.
  55113. var materialLODs = [material.index].concat(properties.ids);
  55114. loader.addLoaderPendingData(material);
  55115. for (var index = 0; index < materialLODs.length; index++) {
  55116. loader.addLoaderNonBlockingPendingData(index);
  55117. }
  55118. // Start with the lowest quality LOD.
  55119. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  55120. return true;
  55121. };
  55122. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  55123. var _this = this;
  55124. var materialLOD = loader.gltf.materials[materialLODs[lod]];
  55125. if (lod !== materialLODs.length - 1) {
  55126. loader.blockPendingTracking = true;
  55127. }
  55128. loader.loadMaterial(materialLOD, function (babylonMaterial, isNew) {
  55129. assign(babylonMaterial, isNew);
  55130. loader.removeLoaderPendingData(lod);
  55131. // Loading is considered complete if this is the lowest quality LOD.
  55132. if (lod === materialLODs.length - 1) {
  55133. loader.removeLoaderPendingData(material);
  55134. }
  55135. if (lod === 0) {
  55136. loader.blockPendingTracking = false;
  55137. return;
  55138. }
  55139. // Load the next LOD when the loader is ready to render and
  55140. // all active material textures of the current LOD are loaded.
  55141. loader.executeWhenRenderReady(function () {
  55142. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  55143. setTimeout(function () {
  55144. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  55145. }, MSFTLOD.MinimalLODDelay);
  55146. });
  55147. });
  55148. });
  55149. };
  55150. /**
  55151. * Specify the minimal delay between LODs in ms (default = 250)
  55152. */
  55153. MSFTLOD.MinimalLODDelay = 250;
  55154. return MSFTLOD;
  55155. }(GLTF2.GLTFLoaderExtension));
  55156. Extensions.MSFTLOD = MSFTLOD;
  55157. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  55158. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  55159. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  55160. })(BABYLON || (BABYLON = {}));
  55161. //# sourceMappingURL=MSFT_lod.js.map
  55162. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  55163. var BABYLON;
  55164. (function (BABYLON) {
  55165. var GLTF2;
  55166. (function (GLTF2) {
  55167. var Extensions;
  55168. (function (Extensions) {
  55169. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  55170. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  55171. function KHRMaterialsPbrSpecularGlossiness() {
  55172. return _super !== null && _super.apply(this, arguments) || this;
  55173. }
  55174. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  55175. get: function () {
  55176. return "KHR_materials_pbrSpecularGlossiness";
  55177. },
  55178. enumerable: true,
  55179. configurable: true
  55180. });
  55181. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  55182. if (!material.extensions) {
  55183. return false;
  55184. }
  55185. var properties = material.extensions[this.name];
  55186. if (!properties) {
  55187. return false;
  55188. }
  55189. loader.createPbrMaterial(material);
  55190. loader.loadMaterialBaseProperties(material);
  55191. this._loadSpecularGlossinessProperties(loader, material, properties);
  55192. assign(material.babylonMaterial, true);
  55193. return true;
  55194. };
  55195. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, material, properties) {
  55196. var babylonMaterial = material.babylonMaterial;
  55197. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  55198. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  55199. babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  55200. if (properties.diffuseTexture) {
  55201. babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  55202. loader.loadMaterialAlphaProperties(material);
  55203. }
  55204. if (properties.specularGlossinessTexture) {
  55205. babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  55206. babylonMaterial.reflectivityTexture.hasAlpha = true;
  55207. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  55208. }
  55209. loader.loadMaterialAlphaProperties(material, properties.diffuseFactor);
  55210. };
  55211. return KHRMaterialsPbrSpecularGlossiness;
  55212. }(GLTF2.GLTFLoaderExtension));
  55213. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  55214. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  55215. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  55216. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  55217. })(BABYLON || (BABYLON = {}));
  55218. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  55219. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  55220. module.exports = BABYLON;
  55221. };