babylon.max.js 2.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648
  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. _this.onCanvasBlurObservable.notifyObservers(_this);
  7735. };
  7736. this._onFocus = function () {
  7737. if (_this.disablePerformanceMonitorInBackground) {
  7738. _this._performanceMonitor.enable();
  7739. }
  7740. _this._windowIsBackground = false;
  7741. _this.onCanvasFocusObservable.notifyObservers(_this);
  7742. };
  7743. this._onCanvasPointerOut = function () {
  7744. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7745. };
  7746. window.addEventListener("blur", this._onBlur);
  7747. window.addEventListener("focus", this._onFocus);
  7748. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  7749. }
  7750. else {
  7751. this._gl = canvasOrContext;
  7752. this._renderingCanvas = this._gl.canvas;
  7753. if (this._gl.renderbufferStorageMultisample) {
  7754. this._webGLVersion = 2.0;
  7755. }
  7756. options.stencil = this._gl.getContextAttributes().stencil;
  7757. }
  7758. // Context lost
  7759. if (!this._doNotHandleContextLost) {
  7760. this._onContextLost = function (evt) {
  7761. evt.preventDefault();
  7762. _this._contextWasLost = true;
  7763. BABYLON.Tools.Warn("WebGL context lost.");
  7764. _this.onContextLostObservable.notifyObservers(_this);
  7765. };
  7766. this._onContextRestored = function (evt) {
  7767. // Rebuild gl context
  7768. _this._initGLContext();
  7769. // Rebuild effects
  7770. _this._rebuildEffects();
  7771. // Rebuild textures
  7772. _this._rebuildInternalTextures();
  7773. // Rebuild buffers
  7774. _this._rebuildBuffers();
  7775. // Cache
  7776. _this.wipeCaches(true);
  7777. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7778. _this.onContextRestoredObservable.notifyObservers(_this);
  7779. _this._contextWasLost = false;
  7780. };
  7781. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7782. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7783. }
  7784. // Viewport
  7785. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7786. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7787. this.resize();
  7788. this._isStencilEnable = options.stencil;
  7789. this._initGLContext();
  7790. if (canvas) {
  7791. // Fullscreen
  7792. this._onFullscreenChange = function () {
  7793. if (document.fullscreen !== undefined) {
  7794. _this.isFullscreen = document.fullscreen;
  7795. }
  7796. else if (document.mozFullScreen !== undefined) {
  7797. _this.isFullscreen = document.mozFullScreen;
  7798. }
  7799. else if (document.webkitIsFullScreen !== undefined) {
  7800. _this.isFullscreen = document.webkitIsFullScreen;
  7801. }
  7802. else if (document.msIsFullScreen !== undefined) {
  7803. _this.isFullscreen = document.msIsFullScreen;
  7804. }
  7805. // Pointer lock
  7806. if (_this.isFullscreen && _this._pointerLockRequested) {
  7807. canvas.requestPointerLock = canvas.requestPointerLock ||
  7808. canvas.msRequestPointerLock ||
  7809. canvas.mozRequestPointerLock ||
  7810. canvas.webkitRequestPointerLock;
  7811. if (canvas.requestPointerLock) {
  7812. canvas.requestPointerLock();
  7813. }
  7814. }
  7815. };
  7816. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7817. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7818. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7819. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7820. // Pointer lock
  7821. this._onPointerLockChange = function () {
  7822. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7823. document.webkitPointerLockElement === canvas ||
  7824. document.msPointerLockElement === canvas ||
  7825. document.pointerLockElement === canvas);
  7826. };
  7827. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7828. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7829. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7830. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7831. this._onVRDisplayPointerRestricted = function () {
  7832. canvas.requestPointerLock();
  7833. };
  7834. this._onVRDisplayPointerUnrestricted = function () {
  7835. document.exitPointerLock();
  7836. };
  7837. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7838. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7839. }
  7840. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7841. Engine.audioEngine = new BABYLON.AudioEngine();
  7842. }
  7843. // Prepare buffer pointers
  7844. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7845. this._currentBufferPointers[i] = new BufferPointer();
  7846. }
  7847. // Load WebVR Devices
  7848. if (options.autoEnableWebVR) {
  7849. this.initWebVR();
  7850. }
  7851. // Detect if we are running on a faulty buggy OS.
  7852. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7853. // Detect if we are running on a faulty buggy desktop OS.
  7854. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7855. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7856. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7857. }
  7858. Object.defineProperty(Engine, "LastCreatedEngine", {
  7859. get: function () {
  7860. if (Engine.Instances.length === 0) {
  7861. return null;
  7862. }
  7863. return Engine.Instances[Engine.Instances.length - 1];
  7864. },
  7865. enumerable: true,
  7866. configurable: true
  7867. });
  7868. Object.defineProperty(Engine, "LastCreatedScene", {
  7869. get: function () {
  7870. var lastCreatedEngine = Engine.LastCreatedEngine;
  7871. if (!lastCreatedEngine) {
  7872. return null;
  7873. }
  7874. if (lastCreatedEngine.scenes.length === 0) {
  7875. return null;
  7876. }
  7877. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7878. },
  7879. enumerable: true,
  7880. configurable: true
  7881. });
  7882. /**
  7883. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7884. */
  7885. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7886. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7887. var engine = Engine.Instances[engineIndex];
  7888. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7889. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7890. }
  7891. }
  7892. };
  7893. Object.defineProperty(Engine, "NEVER", {
  7894. get: function () {
  7895. return Engine._NEVER;
  7896. },
  7897. enumerable: true,
  7898. configurable: true
  7899. });
  7900. Object.defineProperty(Engine, "ALWAYS", {
  7901. get: function () {
  7902. return Engine._ALWAYS;
  7903. },
  7904. enumerable: true,
  7905. configurable: true
  7906. });
  7907. Object.defineProperty(Engine, "LESS", {
  7908. get: function () {
  7909. return Engine._LESS;
  7910. },
  7911. enumerable: true,
  7912. configurable: true
  7913. });
  7914. Object.defineProperty(Engine, "EQUAL", {
  7915. get: function () {
  7916. return Engine._EQUAL;
  7917. },
  7918. enumerable: true,
  7919. configurable: true
  7920. });
  7921. Object.defineProperty(Engine, "LEQUAL", {
  7922. get: function () {
  7923. return Engine._LEQUAL;
  7924. },
  7925. enumerable: true,
  7926. configurable: true
  7927. });
  7928. Object.defineProperty(Engine, "GREATER", {
  7929. get: function () {
  7930. return Engine._GREATER;
  7931. },
  7932. enumerable: true,
  7933. configurable: true
  7934. });
  7935. Object.defineProperty(Engine, "GEQUAL", {
  7936. get: function () {
  7937. return Engine._GEQUAL;
  7938. },
  7939. enumerable: true,
  7940. configurable: true
  7941. });
  7942. Object.defineProperty(Engine, "NOTEQUAL", {
  7943. get: function () {
  7944. return Engine._NOTEQUAL;
  7945. },
  7946. enumerable: true,
  7947. configurable: true
  7948. });
  7949. Object.defineProperty(Engine, "KEEP", {
  7950. get: function () {
  7951. return Engine._KEEP;
  7952. },
  7953. enumerable: true,
  7954. configurable: true
  7955. });
  7956. Object.defineProperty(Engine, "REPLACE", {
  7957. get: function () {
  7958. return Engine._REPLACE;
  7959. },
  7960. enumerable: true,
  7961. configurable: true
  7962. });
  7963. Object.defineProperty(Engine, "INCR", {
  7964. get: function () {
  7965. return Engine._INCR;
  7966. },
  7967. enumerable: true,
  7968. configurable: true
  7969. });
  7970. Object.defineProperty(Engine, "DECR", {
  7971. get: function () {
  7972. return Engine._DECR;
  7973. },
  7974. enumerable: true,
  7975. configurable: true
  7976. });
  7977. Object.defineProperty(Engine, "INVERT", {
  7978. get: function () {
  7979. return Engine._INVERT;
  7980. },
  7981. enumerable: true,
  7982. configurable: true
  7983. });
  7984. Object.defineProperty(Engine, "INCR_WRAP", {
  7985. get: function () {
  7986. return Engine._INCR_WRAP;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Engine, "DECR_WRAP", {
  7992. get: function () {
  7993. return Engine._DECR_WRAP;
  7994. },
  7995. enumerable: true,
  7996. configurable: true
  7997. });
  7998. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7999. get: function () {
  8000. return Engine._ALPHA_DISABLE;
  8001. },
  8002. enumerable: true,
  8003. configurable: true
  8004. });
  8005. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8006. get: function () {
  8007. return Engine._ALPHA_ONEONE;
  8008. },
  8009. enumerable: true,
  8010. configurable: true
  8011. });
  8012. Object.defineProperty(Engine, "ALPHA_ADD", {
  8013. get: function () {
  8014. return Engine._ALPHA_ADD;
  8015. },
  8016. enumerable: true,
  8017. configurable: true
  8018. });
  8019. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8020. get: function () {
  8021. return Engine._ALPHA_COMBINE;
  8022. },
  8023. enumerable: true,
  8024. configurable: true
  8025. });
  8026. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8027. get: function () {
  8028. return Engine._ALPHA_SUBTRACT;
  8029. },
  8030. enumerable: true,
  8031. configurable: true
  8032. });
  8033. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8034. get: function () {
  8035. return Engine._ALPHA_MULTIPLY;
  8036. },
  8037. enumerable: true,
  8038. configurable: true
  8039. });
  8040. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8041. get: function () {
  8042. return Engine._ALPHA_MAXIMIZED;
  8043. },
  8044. enumerable: true,
  8045. configurable: true
  8046. });
  8047. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8048. get: function () {
  8049. return Engine._ALPHA_PREMULTIPLIED;
  8050. },
  8051. enumerable: true,
  8052. configurable: true
  8053. });
  8054. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8055. get: function () {
  8056. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8057. },
  8058. enumerable: true,
  8059. configurable: true
  8060. });
  8061. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8062. get: function () {
  8063. return Engine._ALPHA_INTERPOLATE;
  8064. },
  8065. enumerable: true,
  8066. configurable: true
  8067. });
  8068. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8069. get: function () {
  8070. return Engine._ALPHA_SCREENMODE;
  8071. },
  8072. enumerable: true,
  8073. configurable: true
  8074. });
  8075. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8076. get: function () {
  8077. return Engine._DELAYLOADSTATE_NONE;
  8078. },
  8079. enumerable: true,
  8080. configurable: true
  8081. });
  8082. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8083. get: function () {
  8084. return Engine._DELAYLOADSTATE_LOADED;
  8085. },
  8086. enumerable: true,
  8087. configurable: true
  8088. });
  8089. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8090. get: function () {
  8091. return Engine._DELAYLOADSTATE_LOADING;
  8092. },
  8093. enumerable: true,
  8094. configurable: true
  8095. });
  8096. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8097. get: function () {
  8098. return Engine._DELAYLOADSTATE_NOTLOADED;
  8099. },
  8100. enumerable: true,
  8101. configurable: true
  8102. });
  8103. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8104. get: function () {
  8105. return Engine._TEXTUREFORMAT_ALPHA;
  8106. },
  8107. enumerable: true,
  8108. configurable: true
  8109. });
  8110. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8111. get: function () {
  8112. return Engine._TEXTUREFORMAT_LUMINANCE;
  8113. },
  8114. enumerable: true,
  8115. configurable: true
  8116. });
  8117. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8118. get: function () {
  8119. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8120. },
  8121. enumerable: true,
  8122. configurable: true
  8123. });
  8124. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8125. get: function () {
  8126. return Engine._TEXTUREFORMAT_RGB;
  8127. },
  8128. enumerable: true,
  8129. configurable: true
  8130. });
  8131. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8132. get: function () {
  8133. return Engine._TEXTUREFORMAT_RGBA;
  8134. },
  8135. enumerable: true,
  8136. configurable: true
  8137. });
  8138. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8139. get: function () {
  8140. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8141. },
  8142. enumerable: true,
  8143. configurable: true
  8144. });
  8145. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8146. get: function () {
  8147. return Engine._TEXTURETYPE_FLOAT;
  8148. },
  8149. enumerable: true,
  8150. configurable: true
  8151. });
  8152. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8153. get: function () {
  8154. return Engine._TEXTURETYPE_HALF_FLOAT;
  8155. },
  8156. enumerable: true,
  8157. configurable: true
  8158. });
  8159. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8160. get: function () {
  8161. return Engine._SCALEMODE_FLOOR;
  8162. },
  8163. enumerable: true,
  8164. configurable: true
  8165. });
  8166. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8167. get: function () {
  8168. return Engine._SCALEMODE_NEAREST;
  8169. },
  8170. enumerable: true,
  8171. configurable: true
  8172. });
  8173. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8174. get: function () {
  8175. return Engine._SCALEMODE_CEILING;
  8176. },
  8177. enumerable: true,
  8178. configurable: true
  8179. });
  8180. Object.defineProperty(Engine, "Version", {
  8181. get: function () {
  8182. return "3.1-alpha";
  8183. },
  8184. enumerable: true,
  8185. configurable: true
  8186. });
  8187. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8188. get: function () {
  8189. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8190. },
  8191. enumerable: true,
  8192. configurable: true
  8193. });
  8194. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8195. get: function () {
  8196. return this._webGLVersion < 2 || this.forcePOTTextures;
  8197. },
  8198. enumerable: true,
  8199. configurable: true
  8200. });
  8201. Object.defineProperty(Engine.prototype, "badOS", {
  8202. get: function () {
  8203. return this._badOS;
  8204. },
  8205. enumerable: true,
  8206. configurable: true
  8207. });
  8208. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8209. get: function () {
  8210. return this._badDesktopOS;
  8211. },
  8212. enumerable: true,
  8213. configurable: true
  8214. });
  8215. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8216. get: function () {
  8217. return this._performanceMonitor;
  8218. },
  8219. enumerable: true,
  8220. configurable: true
  8221. });
  8222. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8223. get: function () {
  8224. return this._texturesSupported;
  8225. },
  8226. enumerable: true,
  8227. configurable: true
  8228. });
  8229. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8230. get: function () {
  8231. return this._textureFormatInUse;
  8232. },
  8233. enumerable: true,
  8234. configurable: true
  8235. });
  8236. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8237. // Empty texture
  8238. get: function () {
  8239. if (!this._emptyTexture) {
  8240. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8241. }
  8242. return this._emptyTexture;
  8243. },
  8244. enumerable: true,
  8245. configurable: true
  8246. });
  8247. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8248. get: function () {
  8249. if (!this._emptyCubeTexture) {
  8250. var faceData = new Uint8Array(4);
  8251. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8252. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8253. }
  8254. return this._emptyCubeTexture;
  8255. },
  8256. enumerable: true,
  8257. configurable: true
  8258. });
  8259. Engine.prototype._rebuildInternalTextures = function () {
  8260. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8261. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8262. var internalTexture = currentState_1[_i];
  8263. internalTexture._rebuild();
  8264. }
  8265. };
  8266. Engine.prototype._rebuildEffects = function () {
  8267. for (var key in this._compiledEffects) {
  8268. var effect = this._compiledEffects[key];
  8269. effect._prepareEffect();
  8270. }
  8271. BABYLON.Effect.ResetCache();
  8272. };
  8273. Engine.prototype._rebuildBuffers = function () {
  8274. // Index / Vertex
  8275. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8276. var scene = _a[_i];
  8277. scene.resetCachedMaterial();
  8278. scene._rebuildGeometries();
  8279. scene._rebuildTextures();
  8280. }
  8281. // Uniforms
  8282. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8283. var uniformBuffer = _c[_b];
  8284. uniformBuffer._rebuild();
  8285. }
  8286. };
  8287. Engine.prototype._initGLContext = function () {
  8288. // Caps
  8289. this._caps = new EngineCapabilities();
  8290. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8291. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8292. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8293. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8294. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8295. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8296. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8297. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8298. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8299. // Infos
  8300. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8301. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8302. if (rendererInfo != null) {
  8303. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8304. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8305. }
  8306. if (!this._glVendor) {
  8307. this._glVendor = "Unknown vendor";
  8308. }
  8309. if (!this._glRenderer) {
  8310. this._glRenderer = "Unknown renderer";
  8311. }
  8312. // Constants
  8313. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8314. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8315. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8316. this._gl.DEPTH24_STENCIL8 = 35056;
  8317. // Extensions
  8318. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8319. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8320. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8321. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8322. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8323. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8324. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8325. 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');
  8326. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8327. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8328. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8329. this._caps.highPrecisionShaderSupported = true;
  8330. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8331. // Checks if some of the format renders first to allow the use of webgl inspector.
  8332. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8333. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8334. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8335. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8336. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8337. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8338. if (this._webGLVersion > 1) {
  8339. this._gl.HALF_FLOAT_OES = 0x140B;
  8340. }
  8341. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8342. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8343. // Vertex array object
  8344. if (this._webGLVersion > 1) {
  8345. this._caps.vertexArrayObject = true;
  8346. }
  8347. else {
  8348. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8349. if (vertexArrayObjectExtension != null) {
  8350. this._caps.vertexArrayObject = true;
  8351. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8352. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8353. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8354. }
  8355. else {
  8356. this._caps.vertexArrayObject = false;
  8357. }
  8358. }
  8359. // Instances count
  8360. if (this._webGLVersion > 1) {
  8361. this._caps.instancedArrays = true;
  8362. }
  8363. else {
  8364. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8365. if (instanceExtension != null) {
  8366. this._caps.instancedArrays = true;
  8367. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8368. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8369. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8370. }
  8371. else {
  8372. this._caps.instancedArrays = false;
  8373. }
  8374. }
  8375. // Intelligently add supported compressed formats in order to check for.
  8376. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8377. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8378. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8379. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8380. if (this._caps.astc)
  8381. this.texturesSupported.push('-astc.ktx');
  8382. if (this._caps.s3tc)
  8383. this.texturesSupported.push('-dxt.ktx');
  8384. if (this._caps.pvrtc)
  8385. this.texturesSupported.push('-pvrtc.ktx');
  8386. if (this._caps.etc2)
  8387. this.texturesSupported.push('-etc2.ktx');
  8388. if (this._caps.etc1)
  8389. this.texturesSupported.push('-etc1.ktx');
  8390. if (this._gl.getShaderPrecisionFormat) {
  8391. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8392. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8393. }
  8394. // Depth buffer
  8395. this.setDepthBuffer(true);
  8396. this.setDepthFunctionToLessOrEqual();
  8397. this.setDepthWrite(true);
  8398. };
  8399. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8400. get: function () {
  8401. return this._webGLVersion;
  8402. },
  8403. enumerable: true,
  8404. configurable: true
  8405. });
  8406. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8407. /**
  8408. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8409. */
  8410. get: function () {
  8411. return this._isStencilEnable;
  8412. },
  8413. enumerable: true,
  8414. configurable: true
  8415. });
  8416. Engine.prototype._prepareWorkingCanvas = function () {
  8417. if (this._workingCanvas) {
  8418. return;
  8419. }
  8420. this._workingCanvas = document.createElement("canvas");
  8421. this._workingContext = this._workingCanvas.getContext("2d");
  8422. };
  8423. Engine.prototype.resetTextureCache = function () {
  8424. for (var key in this._activeTexturesCache) {
  8425. this._activeTexturesCache[key] = null;
  8426. }
  8427. };
  8428. Engine.prototype.isDeterministicLockStep = function () {
  8429. return this._deterministicLockstep;
  8430. };
  8431. Engine.prototype.getLockstepMaxSteps = function () {
  8432. return this._lockstepMaxSteps;
  8433. };
  8434. Engine.prototype.getGlInfo = function () {
  8435. return {
  8436. vendor: this._glVendor,
  8437. renderer: this._glRenderer,
  8438. version: this._glVersion
  8439. };
  8440. };
  8441. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8442. if (useScreen === void 0) { useScreen = false; }
  8443. var viewport = camera.viewport;
  8444. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8445. };
  8446. Engine.prototype.getRenderWidth = function (useScreen) {
  8447. if (useScreen === void 0) { useScreen = false; }
  8448. if (!useScreen && this._currentRenderTarget) {
  8449. return this._currentRenderTarget.width;
  8450. }
  8451. return this._gl.drawingBufferWidth;
  8452. };
  8453. Engine.prototype.getRenderHeight = function (useScreen) {
  8454. if (useScreen === void 0) { useScreen = false; }
  8455. if (!useScreen && this._currentRenderTarget) {
  8456. return this._currentRenderTarget.height;
  8457. }
  8458. return this._gl.drawingBufferHeight;
  8459. };
  8460. Engine.prototype.getRenderingCanvas = function () {
  8461. return this._renderingCanvas;
  8462. };
  8463. Engine.prototype.getRenderingCanvasClientRect = function () {
  8464. return this._renderingCanvas.getBoundingClientRect();
  8465. };
  8466. Engine.prototype.setHardwareScalingLevel = function (level) {
  8467. this._hardwareScalingLevel = level;
  8468. this.resize();
  8469. };
  8470. Engine.prototype.getHardwareScalingLevel = function () {
  8471. return this._hardwareScalingLevel;
  8472. };
  8473. Engine.prototype.getLoadedTexturesCache = function () {
  8474. return this._internalTexturesCache;
  8475. };
  8476. Engine.prototype.getCaps = function () {
  8477. return this._caps;
  8478. };
  8479. Object.defineProperty(Engine.prototype, "drawCalls", {
  8480. /** The number of draw calls submitted last frame */
  8481. get: function () {
  8482. return this._drawCalls.current;
  8483. },
  8484. enumerable: true,
  8485. configurable: true
  8486. });
  8487. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8488. get: function () {
  8489. return this._drawCalls;
  8490. },
  8491. enumerable: true,
  8492. configurable: true
  8493. });
  8494. Engine.prototype.getDepthFunction = function () {
  8495. return this._depthCullingState.depthFunc;
  8496. };
  8497. Engine.prototype.setDepthFunction = function (depthFunc) {
  8498. this._depthCullingState.depthFunc = depthFunc;
  8499. };
  8500. Engine.prototype.setDepthFunctionToGreater = function () {
  8501. this._depthCullingState.depthFunc = this._gl.GREATER;
  8502. };
  8503. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8504. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8505. };
  8506. Engine.prototype.setDepthFunctionToLess = function () {
  8507. this._depthCullingState.depthFunc = this._gl.LESS;
  8508. };
  8509. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8510. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8511. };
  8512. Engine.prototype.getStencilBuffer = function () {
  8513. return this._stencilState.stencilTest;
  8514. };
  8515. Engine.prototype.setStencilBuffer = function (enable) {
  8516. this._stencilState.stencilTest = enable;
  8517. };
  8518. Engine.prototype.getStencilMask = function () {
  8519. return this._stencilState.stencilMask;
  8520. };
  8521. Engine.prototype.setStencilMask = function (mask) {
  8522. this._stencilState.stencilMask = mask;
  8523. };
  8524. Engine.prototype.getStencilFunction = function () {
  8525. return this._stencilState.stencilFunc;
  8526. };
  8527. Engine.prototype.getStencilFunctionReference = function () {
  8528. return this._stencilState.stencilFuncRef;
  8529. };
  8530. Engine.prototype.getStencilFunctionMask = function () {
  8531. return this._stencilState.stencilFuncMask;
  8532. };
  8533. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8534. this._stencilState.stencilFunc = stencilFunc;
  8535. };
  8536. Engine.prototype.setStencilFunctionReference = function (reference) {
  8537. this._stencilState.stencilFuncRef = reference;
  8538. };
  8539. Engine.prototype.setStencilFunctionMask = function (mask) {
  8540. this._stencilState.stencilFuncMask = mask;
  8541. };
  8542. Engine.prototype.getStencilOperationFail = function () {
  8543. return this._stencilState.stencilOpStencilFail;
  8544. };
  8545. Engine.prototype.getStencilOperationDepthFail = function () {
  8546. return this._stencilState.stencilOpDepthFail;
  8547. };
  8548. Engine.prototype.getStencilOperationPass = function () {
  8549. return this._stencilState.stencilOpStencilDepthPass;
  8550. };
  8551. Engine.prototype.setStencilOperationFail = function (operation) {
  8552. this._stencilState.stencilOpStencilFail = operation;
  8553. };
  8554. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8555. this._stencilState.stencilOpDepthFail = operation;
  8556. };
  8557. Engine.prototype.setStencilOperationPass = function (operation) {
  8558. this._stencilState.stencilOpStencilDepthPass = operation;
  8559. };
  8560. Engine.prototype.setDitheringState = function (value) {
  8561. if (value) {
  8562. this._gl.enable(this._gl.DITHER);
  8563. }
  8564. else {
  8565. this._gl.disable(this._gl.DITHER);
  8566. }
  8567. };
  8568. /**
  8569. * stop executing a render loop function and remove it from the execution array
  8570. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8571. */
  8572. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8573. if (!renderFunction) {
  8574. this._activeRenderLoops = [];
  8575. return;
  8576. }
  8577. var index = this._activeRenderLoops.indexOf(renderFunction);
  8578. if (index >= 0) {
  8579. this._activeRenderLoops.splice(index, 1);
  8580. }
  8581. };
  8582. Engine.prototype._renderLoop = function () {
  8583. if (!this._contextWasLost) {
  8584. var shouldRender = true;
  8585. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8586. shouldRender = false;
  8587. }
  8588. if (shouldRender) {
  8589. // Start new frame
  8590. this.beginFrame();
  8591. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8592. var renderFunction = this._activeRenderLoops[index];
  8593. renderFunction();
  8594. }
  8595. // Present
  8596. this.endFrame();
  8597. }
  8598. }
  8599. if (this._activeRenderLoops.length > 0) {
  8600. // Register new frame
  8601. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8602. }
  8603. else {
  8604. this._renderingQueueLaunched = false;
  8605. }
  8606. };
  8607. /**
  8608. * Register and execute a render loop. The engine can have more than one render function.
  8609. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8610. * @example
  8611. * engine.runRenderLoop(function () {
  8612. * scene.render()
  8613. * })
  8614. */
  8615. Engine.prototype.runRenderLoop = function (renderFunction) {
  8616. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8617. return;
  8618. }
  8619. this._activeRenderLoops.push(renderFunction);
  8620. if (!this._renderingQueueLaunched) {
  8621. this._renderingQueueLaunched = true;
  8622. this._bindedRenderFunction = this._renderLoop.bind(this);
  8623. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8624. }
  8625. };
  8626. /**
  8627. * Toggle full screen mode.
  8628. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8629. * @param {any} options - an options object to be sent to the requestFullscreen function
  8630. */
  8631. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8632. if (this.isFullscreen) {
  8633. BABYLON.Tools.ExitFullscreen();
  8634. }
  8635. else {
  8636. this._pointerLockRequested = requestPointerLock;
  8637. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8638. }
  8639. };
  8640. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8641. if (stencil === void 0) { stencil = false; }
  8642. this.applyStates();
  8643. var mode = 0;
  8644. if (backBuffer && color) {
  8645. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8646. mode |= this._gl.COLOR_BUFFER_BIT;
  8647. }
  8648. if (depth) {
  8649. this._gl.clearDepth(1.0);
  8650. mode |= this._gl.DEPTH_BUFFER_BIT;
  8651. }
  8652. if (stencil) {
  8653. this._gl.clearStencil(0);
  8654. mode |= this._gl.STENCIL_BUFFER_BIT;
  8655. }
  8656. this._gl.clear(mode);
  8657. };
  8658. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8659. var gl = this._gl;
  8660. // Save state
  8661. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8662. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8663. // Change state
  8664. gl.enable(gl.SCISSOR_TEST);
  8665. gl.scissor(x, y, width, height);
  8666. // Clear
  8667. this.clear(clearColor, true, true, true);
  8668. // Restore state
  8669. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8670. if (curScissor === true) {
  8671. gl.enable(gl.SCISSOR_TEST);
  8672. }
  8673. else {
  8674. gl.disable(gl.SCISSOR_TEST);
  8675. }
  8676. };
  8677. /**
  8678. * Set the WebGL's viewport
  8679. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8680. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8681. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8682. */
  8683. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8684. var width = requiredWidth || this.getRenderWidth();
  8685. var height = requiredHeight || this.getRenderHeight();
  8686. var x = viewport.x || 0;
  8687. var y = viewport.y || 0;
  8688. this._cachedViewport = viewport;
  8689. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8690. };
  8691. /**
  8692. * Directly set the WebGL Viewport
  8693. * The x, y, width & height are directly passed to the WebGL call
  8694. * @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.
  8695. */
  8696. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8697. var currentViewport = this._cachedViewport;
  8698. this._cachedViewport = null;
  8699. this._gl.viewport(x, y, width, height);
  8700. return currentViewport;
  8701. };
  8702. Engine.prototype.beginFrame = function () {
  8703. this._measureFps();
  8704. };
  8705. Engine.prototype.endFrame = function () {
  8706. //force a flush in case we are using a bad OS.
  8707. if (this._badOS) {
  8708. this.flushFramebuffer();
  8709. }
  8710. //submit frame to the vr device, if enabled
  8711. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8712. this._vrDisplayEnabled.submitFrame();
  8713. }
  8714. };
  8715. /**
  8716. * resize the view according to the canvas' size.
  8717. * @example
  8718. * window.addEventListener("resize", function () {
  8719. * engine.resize();
  8720. * });
  8721. */
  8722. Engine.prototype.resize = function () {
  8723. // We're not resizing the size of the canvas while in VR mode & presenting
  8724. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8725. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8726. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8727. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8728. }
  8729. };
  8730. /**
  8731. * force a specific size of the canvas
  8732. * @param {number} width - the new canvas' width
  8733. * @param {number} height - the new canvas' height
  8734. */
  8735. Engine.prototype.setSize = function (width, height) {
  8736. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8737. return;
  8738. }
  8739. this._renderingCanvas.width = width;
  8740. this._renderingCanvas.height = height;
  8741. for (var index = 0; index < this.scenes.length; index++) {
  8742. var scene = this.scenes[index];
  8743. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8744. var cam = scene.cameras[camIndex];
  8745. cam._currentRenderId = 0;
  8746. }
  8747. }
  8748. if (this.onResizeObservable.hasObservers) {
  8749. this.onResizeObservable.notifyObservers(this);
  8750. }
  8751. };
  8752. //WebVR functions
  8753. Engine.prototype.isVRDevicePresent = function (callback) {
  8754. this.getVRDevice(null, function (device) {
  8755. callback(device !== null);
  8756. });
  8757. };
  8758. Engine.prototype.getVRDevice = function (name, callback) {
  8759. if (!this.vrDisplaysPromise) {
  8760. callback(null);
  8761. return;
  8762. }
  8763. this.vrDisplaysPromise.then(function (devices) {
  8764. if (devices.length > 0) {
  8765. if (name) {
  8766. var found = devices.some(function (device) {
  8767. if (device.displayName === name) {
  8768. callback(device);
  8769. return true;
  8770. }
  8771. else {
  8772. return false;
  8773. }
  8774. });
  8775. if (!found) {
  8776. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8777. callback(devices[0]);
  8778. }
  8779. }
  8780. else {
  8781. //choose the first one
  8782. callback(devices[0]);
  8783. }
  8784. }
  8785. else {
  8786. BABYLON.Tools.Error("No WebVR devices found!");
  8787. callback(null);
  8788. }
  8789. });
  8790. };
  8791. Engine.prototype.initWebVR = function () {
  8792. if (!this.vrDisplaysPromise) {
  8793. this._getVRDisplays();
  8794. }
  8795. };
  8796. Engine.prototype.enableVR = function (vrDevice) {
  8797. this._vrDisplayEnabled = vrDevice;
  8798. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8799. };
  8800. Engine.prototype.disableVR = function () {
  8801. if (this._vrDisplayEnabled) {
  8802. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8803. }
  8804. };
  8805. Engine.prototype._getVRDisplays = function () {
  8806. var _this = this;
  8807. var getWebVRDevices = function (devices) {
  8808. _this._vrDisplays = devices.filter(function (device) {
  8809. return device instanceof VRDisplay;
  8810. });
  8811. return _this._vrDisplays;
  8812. };
  8813. if (navigator.getVRDisplays) {
  8814. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8815. }
  8816. };
  8817. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8818. if (this._currentRenderTarget) {
  8819. this.unBindFramebuffer(this._currentRenderTarget);
  8820. }
  8821. this._currentRenderTarget = texture;
  8822. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8823. var gl = this._gl;
  8824. if (texture.isCube) {
  8825. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8826. }
  8827. if (this._cachedViewport && !forceFullscreenViewport) {
  8828. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8829. }
  8830. else {
  8831. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8832. }
  8833. this.wipeCaches();
  8834. };
  8835. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8836. if (this._currentFramebuffer !== framebuffer) {
  8837. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8838. this._currentFramebuffer = framebuffer;
  8839. }
  8840. };
  8841. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8842. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8843. this._currentRenderTarget = null;
  8844. // If MSAA, we need to bitblt back to main texture
  8845. var gl = this._gl;
  8846. if (texture._MSAAFramebuffer) {
  8847. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8848. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8849. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8850. }
  8851. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8852. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8853. gl.generateMipmap(gl.TEXTURE_2D);
  8854. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8855. }
  8856. if (onBeforeUnbind) {
  8857. if (texture._MSAAFramebuffer) {
  8858. // Bind the correct framebuffer
  8859. this.bindUnboundFramebuffer(texture._framebuffer);
  8860. }
  8861. onBeforeUnbind();
  8862. }
  8863. this.bindUnboundFramebuffer(null);
  8864. };
  8865. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8866. if (texture.generateMipMaps) {
  8867. var gl = this._gl;
  8868. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8869. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8870. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8871. }
  8872. };
  8873. Engine.prototype.flushFramebuffer = function () {
  8874. this._gl.flush();
  8875. };
  8876. Engine.prototype.restoreDefaultFramebuffer = function () {
  8877. if (this._currentRenderTarget) {
  8878. this.unBindFramebuffer(this._currentRenderTarget);
  8879. }
  8880. else {
  8881. this.bindUnboundFramebuffer(null);
  8882. }
  8883. if (this._cachedViewport) {
  8884. this.setViewport(this._cachedViewport);
  8885. }
  8886. this.wipeCaches();
  8887. };
  8888. // UBOs
  8889. Engine.prototype.createUniformBuffer = function (elements) {
  8890. var ubo = this._gl.createBuffer();
  8891. this.bindUniformBuffer(ubo);
  8892. if (elements instanceof Float32Array) {
  8893. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8894. }
  8895. else {
  8896. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8897. }
  8898. this.bindUniformBuffer(null);
  8899. ubo.references = 1;
  8900. return ubo;
  8901. };
  8902. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8903. var ubo = this._gl.createBuffer();
  8904. this.bindUniformBuffer(ubo);
  8905. if (elements instanceof Float32Array) {
  8906. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8907. }
  8908. else {
  8909. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8910. }
  8911. this.bindUniformBuffer(null);
  8912. ubo.references = 1;
  8913. return ubo;
  8914. };
  8915. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8916. this.bindUniformBuffer(uniformBuffer);
  8917. if (offset === undefined) {
  8918. offset = 0;
  8919. }
  8920. if (count === undefined) {
  8921. if (elements instanceof Float32Array) {
  8922. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8923. }
  8924. else {
  8925. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8926. }
  8927. }
  8928. else {
  8929. if (elements instanceof Float32Array) {
  8930. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8931. }
  8932. else {
  8933. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8934. }
  8935. }
  8936. this.bindUniformBuffer(null);
  8937. };
  8938. // VBOs
  8939. Engine.prototype._resetVertexBufferBinding = function () {
  8940. this.bindArrayBuffer(null);
  8941. this._cachedVertexBuffers = null;
  8942. };
  8943. Engine.prototype.createVertexBuffer = function (vertices) {
  8944. var vbo = this._gl.createBuffer();
  8945. this.bindArrayBuffer(vbo);
  8946. if (vertices instanceof Float32Array) {
  8947. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8948. }
  8949. else {
  8950. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8951. }
  8952. this._resetVertexBufferBinding();
  8953. vbo.references = 1;
  8954. return vbo;
  8955. };
  8956. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8957. var vbo = this._gl.createBuffer();
  8958. this.bindArrayBuffer(vbo);
  8959. if (vertices instanceof Float32Array) {
  8960. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8961. }
  8962. else {
  8963. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8964. }
  8965. this._resetVertexBufferBinding();
  8966. vbo.references = 1;
  8967. return vbo;
  8968. };
  8969. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8970. this.bindArrayBuffer(vertexBuffer);
  8971. if (offset === undefined) {
  8972. offset = 0;
  8973. }
  8974. if (count === undefined) {
  8975. if (vertices instanceof Float32Array) {
  8976. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8977. }
  8978. else {
  8979. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8980. }
  8981. }
  8982. else {
  8983. if (vertices instanceof Float32Array) {
  8984. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8985. }
  8986. else {
  8987. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8988. }
  8989. }
  8990. this._resetVertexBufferBinding();
  8991. };
  8992. Engine.prototype._resetIndexBufferBinding = function () {
  8993. this.bindIndexBuffer(null);
  8994. this._cachedIndexBuffer = null;
  8995. };
  8996. Engine.prototype.createIndexBuffer = function (indices) {
  8997. var vbo = this._gl.createBuffer();
  8998. this.bindIndexBuffer(vbo);
  8999. // Check for 32 bits indices
  9000. var arrayBuffer;
  9001. var need32Bits = false;
  9002. if (indices instanceof Uint16Array) {
  9003. arrayBuffer = indices;
  9004. }
  9005. else {
  9006. //check 32 bit support
  9007. if (this._caps.uintIndices) {
  9008. if (indices instanceof Uint32Array) {
  9009. arrayBuffer = indices;
  9010. need32Bits = true;
  9011. }
  9012. else {
  9013. //number[] or Int32Array, check if 32 bit is necessary
  9014. for (var index = 0; index < indices.length; index++) {
  9015. if (indices[index] > 65535) {
  9016. need32Bits = true;
  9017. break;
  9018. }
  9019. }
  9020. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9021. }
  9022. }
  9023. else {
  9024. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9025. arrayBuffer = new Uint16Array(indices);
  9026. }
  9027. }
  9028. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  9029. this._resetIndexBufferBinding();
  9030. vbo.references = 1;
  9031. vbo.is32Bits = need32Bits;
  9032. return vbo;
  9033. };
  9034. Engine.prototype.bindArrayBuffer = function (buffer) {
  9035. if (!this._vaoRecordInProgress) {
  9036. this._unbindVertexArrayObject();
  9037. }
  9038. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9039. };
  9040. Engine.prototype.bindUniformBuffer = function (buffer) {
  9041. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9042. };
  9043. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9044. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9045. };
  9046. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9047. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9048. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9049. };
  9050. ;
  9051. Engine.prototype.bindIndexBuffer = function (buffer) {
  9052. if (!this._vaoRecordInProgress) {
  9053. this._unbindVertexArrayObject();
  9054. }
  9055. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9056. };
  9057. Engine.prototype.bindBuffer = function (buffer, target) {
  9058. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9059. this._gl.bindBuffer(target, buffer);
  9060. this._currentBoundBuffer[target] = buffer;
  9061. }
  9062. };
  9063. Engine.prototype.updateArrayBuffer = function (data) {
  9064. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9065. };
  9066. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9067. var pointer = this._currentBufferPointers[indx];
  9068. var changed = false;
  9069. if (!pointer.active) {
  9070. changed = true;
  9071. pointer.active = true;
  9072. pointer.index = indx;
  9073. pointer.size = size;
  9074. pointer.type = type;
  9075. pointer.normalized = normalized;
  9076. pointer.stride = stride;
  9077. pointer.offset = offset;
  9078. pointer.buffer = buffer;
  9079. }
  9080. else {
  9081. if (pointer.buffer !== buffer) {
  9082. pointer.buffer = buffer;
  9083. changed = true;
  9084. }
  9085. if (pointer.size !== size) {
  9086. pointer.size = size;
  9087. changed = true;
  9088. }
  9089. if (pointer.type !== type) {
  9090. pointer.type = type;
  9091. changed = true;
  9092. }
  9093. if (pointer.normalized !== normalized) {
  9094. pointer.normalized = normalized;
  9095. changed = true;
  9096. }
  9097. if (pointer.stride !== stride) {
  9098. pointer.stride = stride;
  9099. changed = true;
  9100. }
  9101. if (pointer.offset !== offset) {
  9102. pointer.offset = offset;
  9103. changed = true;
  9104. }
  9105. }
  9106. if (changed || this._vaoRecordInProgress) {
  9107. this.bindArrayBuffer(buffer);
  9108. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9109. }
  9110. };
  9111. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9112. if (indexBuffer == null) {
  9113. return;
  9114. }
  9115. if (this._cachedIndexBuffer !== indexBuffer) {
  9116. this._cachedIndexBuffer = indexBuffer;
  9117. this.bindIndexBuffer(indexBuffer);
  9118. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9119. }
  9120. };
  9121. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9122. var attributes = effect.getAttributesNames();
  9123. if (!this._vaoRecordInProgress) {
  9124. this._unbindVertexArrayObject();
  9125. }
  9126. this.unbindAllAttributes();
  9127. for (var index = 0; index < attributes.length; index++) {
  9128. var order = effect.getAttributeLocation(index);
  9129. if (order >= 0) {
  9130. var vertexBuffer = vertexBuffers[attributes[index]];
  9131. if (!vertexBuffer) {
  9132. continue;
  9133. }
  9134. this._gl.enableVertexAttribArray(order);
  9135. if (!this._vaoRecordInProgress) {
  9136. this._vertexAttribArraysEnabled[order] = true;
  9137. }
  9138. var buffer = vertexBuffer.getBuffer();
  9139. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9140. if (vertexBuffer.getIsInstanced()) {
  9141. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9142. if (!this._vaoRecordInProgress) {
  9143. this._currentInstanceLocations.push(order);
  9144. this._currentInstanceBuffers.push(buffer);
  9145. }
  9146. }
  9147. }
  9148. }
  9149. };
  9150. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9151. var vao = this._gl.createVertexArray();
  9152. this._vaoRecordInProgress = true;
  9153. this._gl.bindVertexArray(vao);
  9154. this._mustWipeVertexAttributes = true;
  9155. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9156. this.bindIndexBuffer(indexBuffer);
  9157. this._vaoRecordInProgress = false;
  9158. this._gl.bindVertexArray(null);
  9159. return vao;
  9160. };
  9161. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9162. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9163. this._cachedVertexArrayObject = vertexArrayObject;
  9164. this._gl.bindVertexArray(vertexArrayObject);
  9165. this._cachedVertexBuffers = null;
  9166. this._cachedIndexBuffer = null;
  9167. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9168. this._mustWipeVertexAttributes = true;
  9169. }
  9170. };
  9171. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9172. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9173. this._cachedVertexBuffers = vertexBuffer;
  9174. this._cachedEffectForVertexBuffers = effect;
  9175. var attributesCount = effect.getAttributesCount();
  9176. this._unbindVertexArrayObject();
  9177. this.unbindAllAttributes();
  9178. var offset = 0;
  9179. for (var index = 0; index < attributesCount; index++) {
  9180. if (index < vertexDeclaration.length) {
  9181. var order = effect.getAttributeLocation(index);
  9182. if (order >= 0) {
  9183. this._gl.enableVertexAttribArray(order);
  9184. this._vertexAttribArraysEnabled[order] = true;
  9185. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9186. }
  9187. offset += vertexDeclaration[index] * 4;
  9188. }
  9189. }
  9190. }
  9191. this._bindIndexBufferWithCache(indexBuffer);
  9192. };
  9193. Engine.prototype._unbindVertexArrayObject = function () {
  9194. if (!this._cachedVertexArrayObject) {
  9195. return;
  9196. }
  9197. this._cachedVertexArrayObject = null;
  9198. this._gl.bindVertexArray(null);
  9199. };
  9200. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9201. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9202. this._cachedVertexBuffers = vertexBuffers;
  9203. this._cachedEffectForVertexBuffers = effect;
  9204. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9205. }
  9206. this._bindIndexBufferWithCache(indexBuffer);
  9207. };
  9208. Engine.prototype.unbindInstanceAttributes = function () {
  9209. var boundBuffer;
  9210. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9211. var instancesBuffer = this._currentInstanceBuffers[i];
  9212. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9213. boundBuffer = instancesBuffer;
  9214. this.bindArrayBuffer(instancesBuffer);
  9215. }
  9216. var offsetLocation = this._currentInstanceLocations[i];
  9217. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9218. }
  9219. this._currentInstanceBuffers.length = 0;
  9220. this._currentInstanceLocations.length = 0;
  9221. };
  9222. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9223. this._gl.deleteVertexArray(vao);
  9224. };
  9225. Engine.prototype._releaseBuffer = function (buffer) {
  9226. buffer.references--;
  9227. if (buffer.references === 0) {
  9228. this._gl.deleteBuffer(buffer);
  9229. return true;
  9230. }
  9231. return false;
  9232. };
  9233. Engine.prototype.createInstancesBuffer = function (capacity) {
  9234. var buffer = this._gl.createBuffer();
  9235. buffer.capacity = capacity;
  9236. this.bindArrayBuffer(buffer);
  9237. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9238. return buffer;
  9239. };
  9240. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9241. this._gl.deleteBuffer(buffer);
  9242. };
  9243. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9244. this.bindArrayBuffer(instancesBuffer);
  9245. if (data) {
  9246. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9247. }
  9248. if (offsetLocations[0].index !== undefined) {
  9249. var stride = 0;
  9250. for (var i = 0; i < offsetLocations.length; i++) {
  9251. var ai = offsetLocations[i];
  9252. stride += ai.attributeSize * 4;
  9253. }
  9254. for (var i = 0; i < offsetLocations.length; i++) {
  9255. var ai = offsetLocations[i];
  9256. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9257. this._gl.enableVertexAttribArray(ai.index);
  9258. this._vertexAttribArraysEnabled[ai.index] = true;
  9259. }
  9260. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9261. this._gl.vertexAttribDivisor(ai.index, 1);
  9262. this._currentInstanceLocations.push(ai.index);
  9263. this._currentInstanceBuffers.push(instancesBuffer);
  9264. }
  9265. }
  9266. else {
  9267. for (var index = 0; index < 4; index++) {
  9268. var offsetLocation = offsetLocations[index];
  9269. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9270. this._gl.enableVertexAttribArray(offsetLocation);
  9271. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9272. }
  9273. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9274. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9275. this._currentInstanceLocations.push(offsetLocation);
  9276. this._currentInstanceBuffers.push(instancesBuffer);
  9277. }
  9278. }
  9279. };
  9280. Engine.prototype.applyStates = function () {
  9281. this._depthCullingState.apply(this._gl);
  9282. this._stencilState.apply(this._gl);
  9283. this._alphaState.apply(this._gl);
  9284. };
  9285. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9286. // Apply states
  9287. this.applyStates();
  9288. this._drawCalls.addCount(1, false);
  9289. // Render
  9290. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9291. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9292. if (instancesCount) {
  9293. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9294. return;
  9295. }
  9296. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9297. };
  9298. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9299. // Apply states
  9300. this.applyStates();
  9301. this._drawCalls.addCount(1, false);
  9302. if (instancesCount) {
  9303. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9304. return;
  9305. }
  9306. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9307. };
  9308. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9309. // Apply states
  9310. this.applyStates();
  9311. this._drawCalls.addCount(1, false);
  9312. if (instancesCount) {
  9313. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9314. return;
  9315. }
  9316. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9317. };
  9318. // Shaders
  9319. Engine.prototype._releaseEffect = function (effect) {
  9320. if (this._compiledEffects[effect._key]) {
  9321. delete this._compiledEffects[effect._key];
  9322. if (effect.getProgram()) {
  9323. this._gl.deleteProgram(effect.getProgram());
  9324. }
  9325. }
  9326. };
  9327. /**
  9328. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9329. * @param samplers An array of string used to represent textures
  9330. */
  9331. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9332. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9333. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9334. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9335. if (this._compiledEffects[name]) {
  9336. var compiledEffect = this._compiledEffects[name];
  9337. if (onCompiled && compiledEffect.isReady()) {
  9338. onCompiled(compiledEffect);
  9339. }
  9340. return compiledEffect;
  9341. }
  9342. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9343. effect._key = name;
  9344. this._compiledEffects[name] = effect;
  9345. return effect;
  9346. };
  9347. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9348. if (uniformsNames === void 0) { uniformsNames = []; }
  9349. if (samplers === void 0) { samplers = []; }
  9350. if (defines === void 0) { defines = ""; }
  9351. return this.createEffect({
  9352. vertex: "particles",
  9353. fragmentElement: fragmentName
  9354. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9355. };
  9356. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9357. context = context || this._gl;
  9358. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9359. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9360. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9361. var shaderProgram = context.createProgram();
  9362. context.attachShader(shaderProgram, vertexShader);
  9363. context.attachShader(shaderProgram, fragmentShader);
  9364. context.linkProgram(shaderProgram);
  9365. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9366. if (!linked) {
  9367. context.validateProgram(shaderProgram);
  9368. var error = context.getProgramInfoLog(shaderProgram);
  9369. if (error) {
  9370. throw new Error(error);
  9371. }
  9372. }
  9373. context.deleteShader(vertexShader);
  9374. context.deleteShader(fragmentShader);
  9375. return shaderProgram;
  9376. };
  9377. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9378. var results = [];
  9379. for (var index = 0; index < uniformsNames.length; index++) {
  9380. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9381. }
  9382. return results;
  9383. };
  9384. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9385. var results = [];
  9386. for (var index = 0; index < attributesNames.length; index++) {
  9387. try {
  9388. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9389. }
  9390. catch (e) {
  9391. results.push(-1);
  9392. }
  9393. }
  9394. return results;
  9395. };
  9396. Engine.prototype.enableEffect = function (effect) {
  9397. // Use program
  9398. this.setProgram(effect.getProgram());
  9399. this._currentEffect = effect;
  9400. if (effect.onBind) {
  9401. effect.onBind(effect);
  9402. }
  9403. effect.onBindObservable.notifyObservers(effect);
  9404. };
  9405. Engine.prototype.setIntArray = function (uniform, array) {
  9406. if (!uniform)
  9407. return;
  9408. this._gl.uniform1iv(uniform, array);
  9409. };
  9410. Engine.prototype.setIntArray2 = function (uniform, array) {
  9411. if (!uniform || array.length % 2 !== 0)
  9412. return;
  9413. this._gl.uniform2iv(uniform, array);
  9414. };
  9415. Engine.prototype.setIntArray3 = function (uniform, array) {
  9416. if (!uniform || array.length % 3 !== 0)
  9417. return;
  9418. this._gl.uniform3iv(uniform, array);
  9419. };
  9420. Engine.prototype.setIntArray4 = function (uniform, array) {
  9421. if (!uniform || array.length % 4 !== 0)
  9422. return;
  9423. this._gl.uniform4iv(uniform, array);
  9424. };
  9425. Engine.prototype.setFloatArray = function (uniform, array) {
  9426. if (!uniform)
  9427. return;
  9428. this._gl.uniform1fv(uniform, array);
  9429. };
  9430. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9431. if (!uniform || array.length % 2 !== 0)
  9432. return;
  9433. this._gl.uniform2fv(uniform, array);
  9434. };
  9435. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9436. if (!uniform || array.length % 3 !== 0)
  9437. return;
  9438. this._gl.uniform3fv(uniform, array);
  9439. };
  9440. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9441. if (!uniform || array.length % 4 !== 0)
  9442. return;
  9443. this._gl.uniform4fv(uniform, array);
  9444. };
  9445. Engine.prototype.setArray = function (uniform, array) {
  9446. if (!uniform)
  9447. return;
  9448. this._gl.uniform1fv(uniform, array);
  9449. };
  9450. Engine.prototype.setArray2 = function (uniform, array) {
  9451. if (!uniform || array.length % 2 !== 0)
  9452. return;
  9453. this._gl.uniform2fv(uniform, array);
  9454. };
  9455. Engine.prototype.setArray3 = function (uniform, array) {
  9456. if (!uniform || array.length % 3 !== 0)
  9457. return;
  9458. this._gl.uniform3fv(uniform, array);
  9459. };
  9460. Engine.prototype.setArray4 = function (uniform, array) {
  9461. if (!uniform || array.length % 4 !== 0)
  9462. return;
  9463. this._gl.uniform4fv(uniform, array);
  9464. };
  9465. Engine.prototype.setMatrices = function (uniform, matrices) {
  9466. if (!uniform)
  9467. return;
  9468. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9469. };
  9470. Engine.prototype.setMatrix = function (uniform, matrix) {
  9471. if (!uniform)
  9472. return;
  9473. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9474. };
  9475. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9476. if (!uniform)
  9477. return;
  9478. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9479. };
  9480. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9481. if (!uniform)
  9482. return;
  9483. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9484. };
  9485. Engine.prototype.setFloat = function (uniform, value) {
  9486. if (!uniform)
  9487. return;
  9488. this._gl.uniform1f(uniform, value);
  9489. };
  9490. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9491. if (!uniform)
  9492. return;
  9493. this._gl.uniform2f(uniform, x, y);
  9494. };
  9495. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9496. if (!uniform)
  9497. return;
  9498. this._gl.uniform3f(uniform, x, y, z);
  9499. };
  9500. Engine.prototype.setBool = function (uniform, bool) {
  9501. if (!uniform)
  9502. return;
  9503. this._gl.uniform1i(uniform, bool);
  9504. };
  9505. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9506. if (!uniform)
  9507. return;
  9508. this._gl.uniform4f(uniform, x, y, z, w);
  9509. };
  9510. Engine.prototype.setColor3 = function (uniform, color3) {
  9511. if (!uniform)
  9512. return;
  9513. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9514. };
  9515. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9516. if (!uniform)
  9517. return;
  9518. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9519. };
  9520. // States
  9521. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9522. if (zOffset === void 0) { zOffset = 0; }
  9523. if (reverseSide === void 0) { reverseSide = false; }
  9524. // Culling
  9525. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9526. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9527. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9528. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9529. if (culling) {
  9530. this._depthCullingState.cullFace = cullFace;
  9531. this._depthCullingState.cull = true;
  9532. }
  9533. else {
  9534. this._depthCullingState.cull = false;
  9535. }
  9536. }
  9537. // Z offset
  9538. this.setZOffset(zOffset);
  9539. };
  9540. Engine.prototype.setZOffset = function (value) {
  9541. this._depthCullingState.zOffset = value;
  9542. };
  9543. Engine.prototype.getZOffset = function () {
  9544. return this._depthCullingState.zOffset;
  9545. };
  9546. Engine.prototype.setDepthBuffer = function (enable) {
  9547. this._depthCullingState.depthTest = enable;
  9548. };
  9549. Engine.prototype.getDepthWrite = function () {
  9550. return this._depthCullingState.depthMask;
  9551. };
  9552. Engine.prototype.setDepthWrite = function (enable) {
  9553. this._depthCullingState.depthMask = enable;
  9554. };
  9555. Engine.prototype.setColorWrite = function (enable) {
  9556. this._gl.colorMask(enable, enable, enable, enable);
  9557. };
  9558. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9559. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9560. };
  9561. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9562. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9563. if (this._alphaMode === mode) {
  9564. return;
  9565. }
  9566. switch (mode) {
  9567. case Engine.ALPHA_DISABLE:
  9568. this._alphaState.alphaBlend = false;
  9569. break;
  9570. case Engine.ALPHA_PREMULTIPLIED:
  9571. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9572. this._alphaState.alphaBlend = true;
  9573. break;
  9574. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9575. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9576. this._alphaState.alphaBlend = true;
  9577. break;
  9578. case Engine.ALPHA_COMBINE:
  9579. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9580. this._alphaState.alphaBlend = true;
  9581. break;
  9582. case Engine.ALPHA_ONEONE:
  9583. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9584. this._alphaState.alphaBlend = true;
  9585. break;
  9586. case Engine.ALPHA_ADD:
  9587. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9588. this._alphaState.alphaBlend = true;
  9589. break;
  9590. case Engine.ALPHA_SUBTRACT:
  9591. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9592. this._alphaState.alphaBlend = true;
  9593. break;
  9594. case Engine.ALPHA_MULTIPLY:
  9595. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9596. this._alphaState.alphaBlend = true;
  9597. break;
  9598. case Engine.ALPHA_MAXIMIZED:
  9599. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9600. this._alphaState.alphaBlend = true;
  9601. break;
  9602. case Engine.ALPHA_INTERPOLATE:
  9603. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9604. this._alphaState.alphaBlend = true;
  9605. break;
  9606. case Engine.ALPHA_SCREENMODE:
  9607. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9608. this._alphaState.alphaBlend = true;
  9609. break;
  9610. }
  9611. if (!noDepthWriteChange) {
  9612. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9613. }
  9614. this._alphaMode = mode;
  9615. };
  9616. Engine.prototype.getAlphaMode = function () {
  9617. return this._alphaMode;
  9618. };
  9619. Engine.prototype.setAlphaTesting = function (enable) {
  9620. this._alphaTest = enable;
  9621. };
  9622. Engine.prototype.getAlphaTesting = function () {
  9623. return !!this._alphaTest;
  9624. };
  9625. // Textures
  9626. Engine.prototype.wipeCaches = function (bruteForce) {
  9627. if (this.preventCacheWipeBetweenFrames) {
  9628. return;
  9629. }
  9630. this.resetTextureCache();
  9631. this._currentEffect = null;
  9632. // 6/8/2017: deltakosh: Should not be required anymore.
  9633. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9634. if (bruteForce) {
  9635. this._currentProgram = null;
  9636. this._stencilState.reset();
  9637. this._depthCullingState.reset();
  9638. this.setDepthFunctionToLessOrEqual();
  9639. this._alphaState.reset();
  9640. }
  9641. this._cachedVertexBuffers = null;
  9642. this._cachedIndexBuffer = null;
  9643. this._cachedEffectForVertexBuffers = null;
  9644. this._unbindVertexArrayObject();
  9645. this.bindIndexBuffer(null);
  9646. this.bindArrayBuffer(null);
  9647. };
  9648. /**
  9649. * Set the compressed texture format to use, based on the formats you have, and the formats
  9650. * supported by the hardware / browser.
  9651. *
  9652. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9653. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9654. * to API arguments needed to compressed textures. This puts the burden on the container
  9655. * generator to house the arcane code for determining these for current & future formats.
  9656. *
  9657. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9658. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9659. *
  9660. * Note: The result of this call is not taken into account when a texture is base64.
  9661. *
  9662. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9663. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9664. *
  9665. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9666. * @returns The extension selected.
  9667. */
  9668. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9669. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9670. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9671. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9672. return this._textureFormatInUse = this._texturesSupported[i];
  9673. }
  9674. }
  9675. }
  9676. // actively set format to nothing, to allow this to be called more than once
  9677. // and possibly fail the 2nd time
  9678. return this._textureFormatInUse = null;
  9679. };
  9680. Engine.prototype._createTexture = function () {
  9681. return this._gl.createTexture();
  9682. };
  9683. /**
  9684. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9685. * @param {string} urlArg- This contains one of the following:
  9686. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9687. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9688. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9689. *
  9690. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9691. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9692. * @param {Scene} scene- Needed for loading to the correct scene.
  9693. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9694. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9695. * @param {callback} onError- Optional callback to be called upon failure.
  9696. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9697. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9698. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9699. *
  9700. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9701. */
  9702. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9703. var _this = this;
  9704. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9705. if (onLoad === void 0) { onLoad = null; }
  9706. if (onError === void 0) { onError = null; }
  9707. if (buffer === void 0) { buffer = null; }
  9708. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9709. var fromData = url.substr(0, 5) === "data:";
  9710. var fromBlob = url.substr(0, 5) === "blob:";
  9711. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9712. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9713. // establish the file extension, if possible
  9714. var lastDot = url.lastIndexOf('.');
  9715. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9716. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9717. var isTGA = (extension === ".tga");
  9718. // determine if a ktx file should be substituted
  9719. var isKTX = false;
  9720. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9721. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9722. isKTX = true;
  9723. }
  9724. if (scene) {
  9725. scene._addPendingData(texture);
  9726. }
  9727. texture.url = url;
  9728. texture.generateMipMaps = !noMipmap;
  9729. texture.samplingMode = samplingMode;
  9730. texture.invertY = invertY;
  9731. if (!this._doNotHandleContextLost) {
  9732. // Keep a link to the buffer only if we plan to handle context lost
  9733. texture._buffer = buffer;
  9734. }
  9735. if (onLoad) {
  9736. texture.onLoadedObservable.add(onLoad);
  9737. }
  9738. if (!fallBack)
  9739. this._internalTexturesCache.push(texture);
  9740. var onerror = function () {
  9741. if (scene) {
  9742. scene._removePendingData(texture);
  9743. }
  9744. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9745. if (isKTX) {
  9746. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9747. }
  9748. else if (onError) {
  9749. onError();
  9750. }
  9751. };
  9752. var callback;
  9753. // processing for non-image formats
  9754. if (isKTX || isTGA || isDDS) {
  9755. if (isKTX) {
  9756. callback = function (data) {
  9757. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9758. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9759. ktx.uploadLevels(_this._gl, !noMipmap);
  9760. return false;
  9761. }, samplingMode);
  9762. };
  9763. }
  9764. else if (isTGA) {
  9765. callback = function (arrayBuffer) {
  9766. var data = new Uint8Array(arrayBuffer);
  9767. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9768. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9769. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9770. return false;
  9771. }, samplingMode);
  9772. };
  9773. }
  9774. else if (isDDS) {
  9775. callback = function (data) {
  9776. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9777. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9778. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9779. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9780. return false;
  9781. }, samplingMode);
  9782. };
  9783. }
  9784. if (!buffer) {
  9785. BABYLON.Tools.LoadFile(url, function (data) {
  9786. callback(data);
  9787. }, null, scene ? scene.database : null, true, onerror);
  9788. }
  9789. else {
  9790. callback(buffer);
  9791. }
  9792. // image format processing
  9793. }
  9794. else {
  9795. var onload = function (img) {
  9796. if (fromBlob && !_this._doNotHandleContextLost) {
  9797. // We need to store the image if we need to rebuild the texture
  9798. // in case of a webgl context lost
  9799. texture._buffer = img;
  9800. }
  9801. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9802. var gl = _this._gl;
  9803. var isPot = (img.width === potWidth && img.height === potHeight);
  9804. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9805. if (isPot) {
  9806. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9807. return false;
  9808. }
  9809. // Using shaders to rescale because canvas.drawImage is lossy
  9810. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9811. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9812. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9813. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9814. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9815. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9816. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9817. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9818. _this._releaseTexture(source);
  9819. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9820. continuationCallback();
  9821. });
  9822. return true;
  9823. }, samplingMode);
  9824. };
  9825. if (!fromData || isBase64)
  9826. if (buffer instanceof HTMLImageElement) {
  9827. onload(buffer);
  9828. }
  9829. else {
  9830. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9831. }
  9832. else if (buffer instanceof Array || typeof buffer === "string")
  9833. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9834. else
  9835. onload(buffer);
  9836. }
  9837. return texture;
  9838. };
  9839. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9840. var _this = this;
  9841. var rtt = this.createRenderTargetTexture({
  9842. width: destination.width,
  9843. height: destination.height,
  9844. }, {
  9845. generateMipMaps: false,
  9846. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9847. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9848. generateDepthBuffer: false,
  9849. generateStencilBuffer: false
  9850. });
  9851. if (!this._rescalePostProcess) {
  9852. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9853. }
  9854. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9855. _this._rescalePostProcess.onApply = function (effect) {
  9856. effect._bindTexture("textureSampler", source);
  9857. };
  9858. scene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9859. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9860. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9861. _this.unBindFramebuffer(rtt);
  9862. _this._releaseTexture(rtt);
  9863. if (onComplete) {
  9864. onComplete();
  9865. }
  9866. });
  9867. };
  9868. Engine.prototype._getInternalFormat = function (format) {
  9869. var internalFormat = this._gl.RGBA;
  9870. switch (format) {
  9871. case Engine.TEXTUREFORMAT_ALPHA:
  9872. internalFormat = this._gl.ALPHA;
  9873. break;
  9874. case Engine.TEXTUREFORMAT_LUMINANCE:
  9875. internalFormat = this._gl.LUMINANCE;
  9876. break;
  9877. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9878. internalFormat = this._gl.LUMINANCE_ALPHA;
  9879. break;
  9880. case Engine.TEXTUREFORMAT_RGB:
  9881. internalFormat = this._gl.RGB;
  9882. break;
  9883. case Engine.TEXTUREFORMAT_RGBA:
  9884. internalFormat = this._gl.RGBA;
  9885. break;
  9886. }
  9887. return internalFormat;
  9888. };
  9889. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9890. if (compression === void 0) { compression = null; }
  9891. var internalFormat = this._getInternalFormat(format);
  9892. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9893. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9894. if (!this._doNotHandleContextLost) {
  9895. texture._bufferView = data;
  9896. texture.format = format;
  9897. texture.invertY = invertY;
  9898. texture._compression = compression;
  9899. }
  9900. if (texture.width % 4 !== 0) {
  9901. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9902. }
  9903. if (compression) {
  9904. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  9905. }
  9906. else {
  9907. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9908. }
  9909. if (texture.generateMipMaps) {
  9910. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9911. }
  9912. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9913. this.resetTextureCache();
  9914. texture.isReady = true;
  9915. };
  9916. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9917. if (compression === void 0) { compression = null; }
  9918. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  9919. texture.baseWidth = width;
  9920. texture.baseHeight = height;
  9921. texture.width = width;
  9922. texture.height = height;
  9923. texture.format = format;
  9924. texture.generateMipMaps = generateMipMaps;
  9925. texture.samplingMode = samplingMode;
  9926. texture.invertY = invertY;
  9927. texture._compression = compression;
  9928. if (!this._doNotHandleContextLost) {
  9929. texture._bufferView = data;
  9930. }
  9931. this.updateRawTexture(texture, data, format, invertY, compression);
  9932. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9933. // Filters
  9934. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9935. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9936. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9937. if (generateMipMaps) {
  9938. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9939. }
  9940. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9941. this._internalTexturesCache.push(texture);
  9942. return texture;
  9943. };
  9944. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9945. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  9946. texture.baseWidth = width;
  9947. texture.baseHeight = height;
  9948. if (generateMipMaps) {
  9949. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9950. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9951. }
  9952. this.resetTextureCache();
  9953. texture.width = width;
  9954. texture.height = height;
  9955. texture.isReady = false;
  9956. texture.generateMipMaps = generateMipMaps;
  9957. texture.samplingMode = samplingMode;
  9958. this.updateTextureSamplingMode(samplingMode, texture);
  9959. this._internalTexturesCache.push(texture);
  9960. return texture;
  9961. };
  9962. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9963. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9964. if (texture.isCube) {
  9965. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9966. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9967. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9968. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9969. }
  9970. else {
  9971. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9972. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9973. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9974. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9975. }
  9976. texture.samplingMode = samplingMode;
  9977. };
  9978. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9979. if (premulAlpha === void 0) { premulAlpha = false; }
  9980. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9981. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9982. if (premulAlpha) {
  9983. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9984. }
  9985. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9986. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9987. if (texture.generateMipMaps) {
  9988. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9989. }
  9990. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9991. if (premulAlpha) {
  9992. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9993. }
  9994. this.resetTextureCache();
  9995. texture.isReady = true;
  9996. };
  9997. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9998. if (texture._isDisabled) {
  9999. return;
  10000. }
  10001. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10002. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10003. try {
  10004. // Testing video texture support
  10005. if (this._videoTextureSupported === undefined) {
  10006. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10007. if (this._gl.getError() !== 0) {
  10008. this._videoTextureSupported = false;
  10009. }
  10010. else {
  10011. this._videoTextureSupported = true;
  10012. }
  10013. }
  10014. // Copy video through the current working canvas if video texture is not supported
  10015. if (!this._videoTextureSupported) {
  10016. if (!texture._workingCanvas) {
  10017. texture._workingCanvas = document.createElement("canvas");
  10018. texture._workingContext = texture._workingCanvas.getContext("2d");
  10019. texture._workingCanvas.width = texture.width;
  10020. texture._workingCanvas.height = texture.height;
  10021. }
  10022. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10023. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10024. }
  10025. else {
  10026. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10027. }
  10028. if (texture.generateMipMaps) {
  10029. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10030. }
  10031. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10032. this.resetTextureCache();
  10033. texture.isReady = true;
  10034. }
  10035. catch (ex) {
  10036. // Something unexpected
  10037. // Let's disable the texture
  10038. texture._isDisabled = true;
  10039. }
  10040. };
  10041. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10042. var fullOptions = new RenderTargetCreationOptions();
  10043. if (options !== undefined && typeof options === "object") {
  10044. fullOptions.generateMipMaps = options.generateMipMaps;
  10045. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10046. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10047. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10048. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10049. }
  10050. else {
  10051. fullOptions.generateMipMaps = options;
  10052. fullOptions.generateDepthBuffer = true;
  10053. fullOptions.generateStencilBuffer = false;
  10054. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10055. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10056. }
  10057. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10058. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10059. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10060. }
  10061. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10062. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10063. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10064. }
  10065. var gl = this._gl;
  10066. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10067. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10068. var width = size.width || size;
  10069. var height = size.height || size;
  10070. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  10071. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10072. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10073. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10074. }
  10075. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10077. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10078. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10079. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10080. // Create the framebuffer
  10081. var framebuffer = gl.createFramebuffer();
  10082. this.bindUnboundFramebuffer(framebuffer);
  10083. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10084. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  10085. if (fullOptions.generateMipMaps) {
  10086. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10087. }
  10088. // Unbind
  10089. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10090. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10091. this.bindUnboundFramebuffer(null);
  10092. texture._framebuffer = framebuffer;
  10093. texture.baseWidth = width;
  10094. texture.baseHeight = height;
  10095. texture.width = width;
  10096. texture.height = height;
  10097. texture.isReady = true;
  10098. texture.samples = 1;
  10099. texture.generateMipMaps = fullOptions.generateMipMaps;
  10100. texture.samplingMode = fullOptions.samplingMode;
  10101. texture.type = fullOptions.type;
  10102. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10103. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  10104. this.resetTextureCache();
  10105. this._internalTexturesCache.push(texture);
  10106. return texture;
  10107. };
  10108. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10109. var generateMipMaps = false;
  10110. var generateDepthBuffer = true;
  10111. var generateStencilBuffer = false;
  10112. var generateDepthTexture = false;
  10113. var textureCount = 1;
  10114. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10115. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10116. var types = [], samplingModes = [];
  10117. if (options !== undefined) {
  10118. generateMipMaps = options.generateMipMaps;
  10119. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10120. generateStencilBuffer = options.generateStencilBuffer;
  10121. generateDepthTexture = options.generateDepthTexture;
  10122. textureCount = options.textureCount || 1;
  10123. if (options.types) {
  10124. types = options.types;
  10125. }
  10126. if (options.samplingModes) {
  10127. samplingModes = options.samplingModes;
  10128. }
  10129. }
  10130. var gl = this._gl;
  10131. // Create the framebuffer
  10132. var framebuffer = gl.createFramebuffer();
  10133. this.bindUnboundFramebuffer(framebuffer);
  10134. var width = size.width || size;
  10135. var height = size.height || size;
  10136. var textures = [];
  10137. var attachments = [];
  10138. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10139. for (var i = 0; i < textureCount; i++) {
  10140. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10141. var type = types[i] || defaultType;
  10142. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10143. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10144. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10145. }
  10146. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10147. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10148. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10149. }
  10150. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10151. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10152. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10153. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10154. }
  10155. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10156. var attachment = gl["COLOR_ATTACHMENT" + i];
  10157. textures.push(texture);
  10158. attachments.push(attachment);
  10159. gl.activeTexture(gl["TEXTURE" + i]);
  10160. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10161. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10162. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10163. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10164. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10165. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10166. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10167. if (generateMipMaps) {
  10168. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10169. }
  10170. // Unbind
  10171. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10172. texture._framebuffer = framebuffer;
  10173. texture._depthStencilBuffer = depthStencilBuffer;
  10174. texture.baseWidth = width;
  10175. texture.baseHeight = height;
  10176. texture.width = width;
  10177. texture.height = height;
  10178. texture.isReady = true;
  10179. texture.samples = 1;
  10180. texture.generateMipMaps = generateMipMaps;
  10181. texture.samplingMode = samplingMode;
  10182. texture.type = type;
  10183. texture._generateDepthBuffer = generateDepthBuffer;
  10184. texture._generateStencilBuffer = generateStencilBuffer;
  10185. this._internalTexturesCache.push(texture);
  10186. }
  10187. if (generateDepthTexture) {
  10188. // Depth texture
  10189. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10190. gl.activeTexture(gl.TEXTURE0);
  10191. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10192. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10193. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10194. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10195. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10196. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  10197. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10198. depthTexture._framebuffer = framebuffer;
  10199. depthTexture.baseWidth = width;
  10200. depthTexture.baseHeight = height;
  10201. depthTexture.width = width;
  10202. depthTexture.height = height;
  10203. depthTexture.isReady = true;
  10204. depthTexture.samples = 1;
  10205. depthTexture.generateMipMaps = generateMipMaps;
  10206. depthTexture.samplingMode = gl.NEAREST;
  10207. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10208. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10209. textures.push(depthTexture);
  10210. this._internalTexturesCache.push(depthTexture);
  10211. }
  10212. gl.drawBuffers(attachments);
  10213. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10214. this.bindUnboundFramebuffer(null);
  10215. this.resetTextureCache();
  10216. return textures;
  10217. };
  10218. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10219. if (samples === void 0) { samples = 1; }
  10220. var depthStencilBuffer = null;
  10221. var gl = this._gl;
  10222. // Create the depth/stencil buffer
  10223. if (generateStencilBuffer) {
  10224. depthStencilBuffer = gl.createRenderbuffer();
  10225. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10226. if (samples > 1) {
  10227. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10228. }
  10229. else {
  10230. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10231. }
  10232. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10233. }
  10234. else if (generateDepthBuffer) {
  10235. depthStencilBuffer = gl.createRenderbuffer();
  10236. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10237. if (samples > 1) {
  10238. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10239. }
  10240. else {
  10241. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10242. }
  10243. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10244. }
  10245. return depthStencilBuffer;
  10246. };
  10247. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10248. if (this.webGLVersion < 2) {
  10249. return 1;
  10250. }
  10251. if (texture.samples === samples) {
  10252. return samples;
  10253. }
  10254. var gl = this._gl;
  10255. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10256. // Dispose previous render buffers
  10257. if (texture._depthStencilBuffer) {
  10258. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10259. }
  10260. if (texture._MSAAFramebuffer) {
  10261. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10262. }
  10263. if (texture._MSAARenderBuffer) {
  10264. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10265. }
  10266. if (samples > 1) {
  10267. texture._MSAAFramebuffer = gl.createFramebuffer();
  10268. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10269. var colorRenderbuffer = gl.createRenderbuffer();
  10270. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10271. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10272. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10273. texture._MSAARenderBuffer = colorRenderbuffer;
  10274. }
  10275. else {
  10276. this.bindUnboundFramebuffer(texture._framebuffer);
  10277. }
  10278. texture.samples = samples;
  10279. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10280. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10281. this.bindUnboundFramebuffer(null);
  10282. return samples;
  10283. };
  10284. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10285. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10286. };
  10287. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10288. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10289. };
  10290. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10291. var gl = this._gl;
  10292. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10293. var generateMipMaps = true;
  10294. var generateDepthBuffer = true;
  10295. var generateStencilBuffer = false;
  10296. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10297. if (options !== undefined) {
  10298. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10299. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10300. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10301. if (options.samplingMode !== undefined) {
  10302. samplingMode = options.samplingMode;
  10303. }
  10304. }
  10305. texture.isCube = true;
  10306. texture.generateMipMaps = generateMipMaps;
  10307. texture.samples = 1;
  10308. texture.samplingMode = samplingMode;
  10309. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10310. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10311. for (var face = 0; face < 6; face++) {
  10312. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10313. }
  10314. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10315. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10316. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10317. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10318. // Create the framebuffer
  10319. var framebuffer = gl.createFramebuffer();
  10320. this.bindUnboundFramebuffer(framebuffer);
  10321. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10322. // Mipmaps
  10323. if (texture.generateMipMaps) {
  10324. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10325. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10326. }
  10327. // Unbind
  10328. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10329. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10330. this.bindUnboundFramebuffer(null);
  10331. texture._framebuffer = framebuffer;
  10332. texture.width = size;
  10333. texture.height = size;
  10334. texture.isReady = true;
  10335. this.resetTextureCache();
  10336. this._internalTexturesCache.push(texture);
  10337. return texture;
  10338. };
  10339. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10340. var _this = this;
  10341. if (onError === void 0) { onError = null; }
  10342. if (forcedExtension === void 0) { forcedExtension = null; }
  10343. var callback = function (loadData) {
  10344. if (!loadData) {
  10345. if (onLoad) {
  10346. onLoad(null);
  10347. }
  10348. return;
  10349. }
  10350. var texture = loadData.texture;
  10351. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10352. texture._lodGenerationScale = scale;
  10353. texture._lodGenerationOffset = offset;
  10354. if (_this._caps.textureLOD) {
  10355. // Do not add extra process if texture lod is supported.
  10356. if (onLoad) {
  10357. onLoad(texture);
  10358. }
  10359. return;
  10360. }
  10361. var mipSlices = 3;
  10362. var gl = _this._gl;
  10363. var width = loadData.width;
  10364. if (!width) {
  10365. return;
  10366. }
  10367. var textures = [];
  10368. for (var i = 0; i < mipSlices; i++) {
  10369. //compute LOD from even spacing in smoothness (matching shader calculation)
  10370. var smoothness = i / (mipSlices - 1);
  10371. var roughness = 1 - smoothness;
  10372. var minLODIndex = offset; // roughness = 0
  10373. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10374. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10375. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10376. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10377. glTextureFromLod.isCube = true;
  10378. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10379. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10380. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10381. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10382. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10383. if (loadData.isDDS) {
  10384. var info = loadData.info;
  10385. var data = loadData.data;
  10386. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10387. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10388. }
  10389. else {
  10390. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10391. }
  10392. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10393. // Wrap in a base texture for easy binding.
  10394. var lodTexture = new BABYLON.BaseTexture(scene);
  10395. lodTexture.isCube = true;
  10396. lodTexture._texture = glTextureFromLod;
  10397. glTextureFromLod.isReady = true;
  10398. textures.push(lodTexture);
  10399. }
  10400. texture._lodTextureHigh = textures[2];
  10401. texture._lodTextureMid = textures[1];
  10402. texture._lodTextureLow = textures[0];
  10403. if (onLoad) {
  10404. onLoad(texture);
  10405. }
  10406. };
  10407. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10408. };
  10409. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10410. var _this = this;
  10411. if (onLoad === void 0) { onLoad = null; }
  10412. if (onError === void 0) { onError = null; }
  10413. if (forcedExtension === void 0) { forcedExtension = null; }
  10414. var gl = this._gl;
  10415. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10416. texture.isCube = true;
  10417. texture.url = rootUrl;
  10418. texture.generateMipMaps = !noMipmap;
  10419. if (!this._doNotHandleContextLost) {
  10420. texture._extension = forcedExtension;
  10421. texture._files = files;
  10422. }
  10423. var isKTX = false;
  10424. var isDDS = false;
  10425. var lastDot = rootUrl.lastIndexOf('.');
  10426. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10427. if (this._textureFormatInUse) {
  10428. extension = this._textureFormatInUse;
  10429. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10430. isKTX = true;
  10431. }
  10432. else {
  10433. isDDS = (extension === ".dds");
  10434. }
  10435. if (isKTX) {
  10436. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10437. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10438. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10439. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10440. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10441. ktx.uploadLevels(_this._gl, !noMipmap);
  10442. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10443. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10444. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10445. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10446. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10447. _this.resetTextureCache();
  10448. texture.width = ktx.pixelWidth;
  10449. texture.height = ktx.pixelHeight;
  10450. texture.isReady = true;
  10451. }, null, null, true, onError);
  10452. }
  10453. else if (isDDS) {
  10454. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10455. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10456. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10457. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10458. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10459. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10460. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10461. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10462. }
  10463. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10464. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10465. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10466. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10467. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10468. _this.resetTextureCache();
  10469. texture.width = info.width;
  10470. texture.height = info.height;
  10471. texture.isReady = true;
  10472. texture.type = info.textureType;
  10473. if (onLoad) {
  10474. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10475. }
  10476. }, null, null, true, onError);
  10477. }
  10478. else {
  10479. cascadeLoad(rootUrl, scene, function (imgs) {
  10480. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10481. var height = width;
  10482. _this._prepareWorkingCanvas();
  10483. _this._workingCanvas.width = width;
  10484. _this._workingCanvas.height = height;
  10485. var faces = [
  10486. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10487. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10488. ];
  10489. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10490. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10491. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10492. for (var index = 0; index < faces.length; index++) {
  10493. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10494. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10495. }
  10496. if (!noMipmap) {
  10497. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10498. }
  10499. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10500. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10501. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10502. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10503. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10504. _this.resetTextureCache();
  10505. texture.width = width;
  10506. texture.height = height;
  10507. texture.isReady = true;
  10508. texture.format = format;
  10509. texture.onLoadedObservable.notifyObservers(texture);
  10510. texture.onLoadedObservable.clear();
  10511. if (onLoad) {
  10512. onLoad();
  10513. }
  10514. }, files, onError);
  10515. }
  10516. this._internalTexturesCache.push(texture);
  10517. return texture;
  10518. };
  10519. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10520. if (compression === void 0) { compression = null; }
  10521. if (level === void 0) { level = 0; }
  10522. texture._bufferViewArray = data;
  10523. texture.format = format;
  10524. texture.type = type;
  10525. texture.invertY = invertY;
  10526. texture._compression = compression;
  10527. var gl = this._gl;
  10528. var textureType = this._getWebGLTextureType(type);
  10529. var internalFormat = this._getInternalFormat(format);
  10530. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10531. var needConversion = false;
  10532. if (internalFormat === gl.RGB) {
  10533. internalFormat = gl.RGBA;
  10534. needConversion = true;
  10535. }
  10536. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10537. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10538. if (texture.width % 4 !== 0) {
  10539. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10540. }
  10541. // Data are known to be in +X +Y +Z -X -Y -Z
  10542. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10543. var faceData = data[faceIndex];
  10544. if (compression) {
  10545. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10546. }
  10547. else {
  10548. if (needConversion) {
  10549. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10550. }
  10551. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10552. }
  10553. }
  10554. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10555. if (isPot && texture.generateMipMaps && level === 0) {
  10556. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10557. }
  10558. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10559. this.resetTextureCache();
  10560. texture.isReady = true;
  10561. };
  10562. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10563. if (compression === void 0) { compression = null; }
  10564. var gl = this._gl;
  10565. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10566. texture.isCube = true;
  10567. texture.generateMipMaps = generateMipMaps;
  10568. texture.format = format;
  10569. texture.type = type;
  10570. if (!this._doNotHandleContextLost) {
  10571. texture._bufferViewArray = data;
  10572. }
  10573. var textureType = this._getWebGLTextureType(type);
  10574. var internalFormat = this._getInternalFormat(format);
  10575. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10576. var needConversion = false;
  10577. if (internalFormat === gl.RGB) {
  10578. internalFormat = gl.RGBA;
  10579. needConversion = true;
  10580. }
  10581. var width = size;
  10582. var height = width;
  10583. texture.width = width;
  10584. texture.height = height;
  10585. // Double check on POT to generate Mips.
  10586. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10587. if (!isPot) {
  10588. generateMipMaps = false;
  10589. }
  10590. // Upload data if needed. The texture won't be ready until then.
  10591. if (data) {
  10592. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10593. }
  10594. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10595. // Filters
  10596. if (data && generateMipMaps) {
  10597. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10598. }
  10599. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10600. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10601. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10602. }
  10603. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10604. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10605. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10606. }
  10607. else {
  10608. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10609. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10610. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10611. }
  10612. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10613. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10614. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10615. return texture;
  10616. };
  10617. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10618. var _this = this;
  10619. if (onLoad === void 0) { onLoad = null; }
  10620. if (onError === void 0) { onError = null; }
  10621. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10622. if (invertY === void 0) { invertY = false; }
  10623. var gl = this._gl;
  10624. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10625. scene._addPendingData(texture);
  10626. texture.url = url;
  10627. this._internalTexturesCache.push(texture);
  10628. var onerror = function () {
  10629. scene._removePendingData(texture);
  10630. if (onError) {
  10631. onError();
  10632. }
  10633. };
  10634. var internalCallback = function (data) {
  10635. var width = texture.width;
  10636. var height = texture.height;
  10637. var faceDataArrays = callback(data);
  10638. if (mipmmapGenerator) {
  10639. var textureType = _this._getWebGLTextureType(type);
  10640. var internalFormat = _this._getInternalFormat(format);
  10641. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10642. var needConversion = false;
  10643. if (internalFormat === gl.RGB) {
  10644. internalFormat = gl.RGBA;
  10645. needConversion = true;
  10646. }
  10647. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10648. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10649. var mipData = mipmmapGenerator(faceDataArrays);
  10650. for (var level = 0; level < mipData.length; level++) {
  10651. var mipSize = width >> level;
  10652. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10653. var mipFaceData = mipData[level][faceIndex];
  10654. if (needConversion) {
  10655. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10656. }
  10657. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10658. }
  10659. }
  10660. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10661. }
  10662. else {
  10663. texture.generateMipMaps = !noMipmap;
  10664. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10665. }
  10666. texture.isReady = true;
  10667. _this.resetTextureCache();
  10668. scene._removePendingData(texture);
  10669. if (onLoad) {
  10670. onLoad();
  10671. }
  10672. };
  10673. BABYLON.Tools.LoadFile(url, function (data) {
  10674. internalCallback(data);
  10675. }, onerror, scene.database, true);
  10676. return texture;
  10677. };
  10678. ;
  10679. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10680. var gl = this._gl;
  10681. if (!gl) {
  10682. return;
  10683. }
  10684. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10685. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10686. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10687. if (!noMipmap && !isCompressed) {
  10688. gl.generateMipmap(gl.TEXTURE_2D);
  10689. }
  10690. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10691. this.resetTextureCache();
  10692. if (scene) {
  10693. scene._removePendingData(texture);
  10694. }
  10695. texture.onLoadedObservable.notifyObservers(texture);
  10696. texture.onLoadedObservable.clear();
  10697. };
  10698. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10699. var _this = this;
  10700. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10701. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10702. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10703. var gl = this._gl;
  10704. if (!gl) {
  10705. return;
  10706. }
  10707. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10708. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10709. texture.baseWidth = width;
  10710. texture.baseHeight = height;
  10711. texture.width = potWidth;
  10712. texture.height = potHeight;
  10713. texture.isReady = true;
  10714. if (processFunction(potWidth, potHeight, function () {
  10715. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10716. })) {
  10717. // Returning as texture needs extra async steps
  10718. return;
  10719. }
  10720. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10721. };
  10722. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10723. // Create new RGBA data container.
  10724. var rgbaData;
  10725. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10726. rgbaData = new Float32Array(width * height * 4);
  10727. }
  10728. else {
  10729. rgbaData = new Uint32Array(width * height * 4);
  10730. }
  10731. // Convert each pixel.
  10732. for (var x = 0; x < width; x++) {
  10733. for (var y = 0; y < height; y++) {
  10734. var index = (y * width + x) * 3;
  10735. var newIndex = (y * width + x) * 4;
  10736. // Map Old Value to new value.
  10737. rgbaData[newIndex + 0] = rgbData[index + 0];
  10738. rgbaData[newIndex + 1] = rgbData[index + 1];
  10739. rgbaData[newIndex + 2] = rgbData[index + 2];
  10740. // Add fully opaque alpha channel.
  10741. rgbaData[newIndex + 3] = 1;
  10742. }
  10743. }
  10744. return rgbaData;
  10745. };
  10746. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10747. var gl = this._gl;
  10748. if (texture._framebuffer) {
  10749. gl.deleteFramebuffer(texture._framebuffer);
  10750. texture._framebuffer = null;
  10751. }
  10752. if (texture._depthStencilBuffer) {
  10753. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10754. texture._depthStencilBuffer = null;
  10755. }
  10756. if (texture._MSAAFramebuffer) {
  10757. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10758. texture._MSAAFramebuffer = null;
  10759. }
  10760. if (texture._MSAARenderBuffer) {
  10761. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10762. texture._MSAARenderBuffer = null;
  10763. }
  10764. };
  10765. Engine.prototype._releaseTexture = function (texture) {
  10766. var gl = this._gl;
  10767. this._releaseFramebufferObjects(texture);
  10768. gl.deleteTexture(texture._webGLTexture);
  10769. // Unbind channels
  10770. this.unbindAllTextures();
  10771. var index = this._internalTexturesCache.indexOf(texture);
  10772. if (index !== -1) {
  10773. this._internalTexturesCache.splice(index, 1);
  10774. }
  10775. // Integrated fixed lod samplers.
  10776. if (texture._lodTextureHigh) {
  10777. texture._lodTextureHigh.dispose();
  10778. }
  10779. if (texture._lodTextureMid) {
  10780. texture._lodTextureMid.dispose();
  10781. }
  10782. if (texture._lodTextureLow) {
  10783. texture._lodTextureLow.dispose();
  10784. }
  10785. };
  10786. Engine.prototype.setProgram = function (program) {
  10787. if (this._currentProgram !== program) {
  10788. this._gl.useProgram(program);
  10789. this._currentProgram = program;
  10790. }
  10791. };
  10792. Engine.prototype.bindSamplers = function (effect) {
  10793. this.setProgram(effect.getProgram());
  10794. var samplers = effect.getSamplers();
  10795. for (var index = 0; index < samplers.length; index++) {
  10796. var uniform = effect.getUniform(samplers[index]);
  10797. this._gl.uniform1i(uniform, index);
  10798. }
  10799. this._currentEffect = null;
  10800. };
  10801. Engine.prototype.activateTexture = function (texture) {
  10802. if (this._activeTexture !== texture) {
  10803. this._gl.activeTexture(texture);
  10804. this._activeTexture = texture;
  10805. }
  10806. };
  10807. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10808. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10809. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10810. this._activeTexturesCache[this._activeTexture] = texture;
  10811. }
  10812. };
  10813. Engine.prototype._bindTexture = function (channel, texture) {
  10814. if (channel < 0) {
  10815. return;
  10816. }
  10817. this.activateTexture(this._gl.TEXTURE0 + channel);
  10818. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10819. };
  10820. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10821. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10822. };
  10823. Engine.prototype.unbindAllTextures = function () {
  10824. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10825. this.activateTexture(this._gl["TEXTURE" + channel]);
  10826. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10827. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10828. }
  10829. };
  10830. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10831. if (channel < 0) {
  10832. return;
  10833. }
  10834. this._gl.uniform1i(uniform, channel);
  10835. this._setTexture(channel, texture);
  10836. };
  10837. Engine.prototype._setTexture = function (channel, texture) {
  10838. // Not ready?
  10839. if (!texture) {
  10840. if (this._activeTexturesCache[channel] != null) {
  10841. this.activateTexture(this._gl["TEXTURE" + channel]);
  10842. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10843. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10844. }
  10845. return;
  10846. }
  10847. // Video
  10848. var alreadyActivated = false;
  10849. if (texture.video) {
  10850. this.activateTexture(this._gl["TEXTURE" + channel]);
  10851. alreadyActivated = true;
  10852. texture.update();
  10853. }
  10854. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10855. texture.delayLoad();
  10856. return;
  10857. }
  10858. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10859. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10860. if (this._activeTexturesCache[channel] === internalTexture) {
  10861. return;
  10862. }
  10863. if (!alreadyActivated) {
  10864. this.activateTexture(this._gl["TEXTURE" + channel]);
  10865. }
  10866. if (internalTexture.isCube) {
  10867. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10868. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10869. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10870. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10871. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10872. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10873. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10874. }
  10875. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10876. }
  10877. else {
  10878. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10879. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10880. internalTexture._cachedWrapU = texture.wrapU;
  10881. switch (texture.wrapU) {
  10882. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10883. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10884. break;
  10885. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10886. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10887. break;
  10888. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10889. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10890. break;
  10891. }
  10892. }
  10893. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10894. internalTexture._cachedWrapV = texture.wrapV;
  10895. switch (texture.wrapV) {
  10896. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10897. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10898. break;
  10899. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10900. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10901. break;
  10902. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10903. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10904. break;
  10905. }
  10906. }
  10907. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10908. }
  10909. };
  10910. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10911. if (channel < 0) {
  10912. return;
  10913. }
  10914. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10915. this._textureUnits = new Int32Array(textures.length);
  10916. }
  10917. for (var i = 0; i < textures.length; i++) {
  10918. this._textureUnits[i] = channel + i;
  10919. }
  10920. this._gl.uniform1iv(uniform, this._textureUnits);
  10921. for (var index = 0; index < textures.length; index++) {
  10922. this._setTexture(channel + index, textures[index]);
  10923. }
  10924. };
  10925. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10926. var internalTexture = texture.getInternalTexture();
  10927. if (!internalTexture) {
  10928. return;
  10929. }
  10930. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10931. var value = texture.anisotropicFilteringLevel;
  10932. if (internalTexture.samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10933. value = 1;
  10934. }
  10935. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  10936. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10937. internalTexture._cachedAnisotropicFilteringLevel = value;
  10938. }
  10939. };
  10940. Engine.prototype.readPixels = function (x, y, width, height) {
  10941. var data = new Uint8Array(height * width * 4);
  10942. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10943. return data;
  10944. };
  10945. /**
  10946. * Add an externaly attached data from its key.
  10947. * This method call will fail and return false, if such key already exists.
  10948. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10949. * @param key the unique key that identifies the data
  10950. * @param data the data object to associate to the key for this Engine instance
  10951. * @return true if no such key were already present and the data was added successfully, false otherwise
  10952. */
  10953. Engine.prototype.addExternalData = function (key, data) {
  10954. if (!this._externalData) {
  10955. this._externalData = new BABYLON.StringDictionary();
  10956. }
  10957. return this._externalData.add(key, data);
  10958. };
  10959. /**
  10960. * Get an externaly attached data from its key
  10961. * @param key the unique key that identifies the data
  10962. * @return the associated data, if present (can be null), or undefined if not present
  10963. */
  10964. Engine.prototype.getExternalData = function (key) {
  10965. if (!this._externalData) {
  10966. this._externalData = new BABYLON.StringDictionary();
  10967. }
  10968. return this._externalData.get(key);
  10969. };
  10970. /**
  10971. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10972. * @param key the unique key that identifies the data
  10973. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10974. * @return the associated data, can be null if the factory returned null.
  10975. */
  10976. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10977. if (!this._externalData) {
  10978. this._externalData = new BABYLON.StringDictionary();
  10979. }
  10980. return this._externalData.getOrAddWithFactory(key, factory);
  10981. };
  10982. /**
  10983. * Remove an externaly attached data from the Engine instance
  10984. * @param key the unique key that identifies the data
  10985. * @return true if the data was successfully removed, false if it doesn't exist
  10986. */
  10987. Engine.prototype.removeExternalData = function (key) {
  10988. if (!this._externalData) {
  10989. this._externalData = new BABYLON.StringDictionary();
  10990. }
  10991. return this._externalData.remove(key);
  10992. };
  10993. Engine.prototype.unbindAllAttributes = function () {
  10994. if (this._mustWipeVertexAttributes) {
  10995. this._mustWipeVertexAttributes = false;
  10996. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10997. this._gl.disableVertexAttribArray(i);
  10998. this._vertexAttribArraysEnabled[i] = false;
  10999. this._currentBufferPointers[i].active = false;
  11000. }
  11001. return;
  11002. }
  11003. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11004. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11005. continue;
  11006. }
  11007. this._gl.disableVertexAttribArray(i);
  11008. this._vertexAttribArraysEnabled[i] = false;
  11009. this._currentBufferPointers[i].active = false;
  11010. }
  11011. };
  11012. Engine.prototype.releaseEffects = function () {
  11013. for (var name in this._compiledEffects) {
  11014. this._gl.deleteProgram(this._compiledEffects[name]._program);
  11015. }
  11016. this._compiledEffects = {};
  11017. };
  11018. // Dispose
  11019. Engine.prototype.dispose = function () {
  11020. this.hideLoadingUI();
  11021. this.stopRenderLoop();
  11022. // Release postProcesses
  11023. while (this.postProcesses.length) {
  11024. this.postProcesses[0].dispose();
  11025. }
  11026. // Empty texture
  11027. if (this._emptyTexture) {
  11028. this._releaseTexture(this._emptyTexture);
  11029. this._emptyTexture = null;
  11030. }
  11031. if (this._emptyCubeTexture) {
  11032. this._releaseTexture(this._emptyCubeTexture);
  11033. this._emptyCubeTexture = null;
  11034. }
  11035. // Rescale PP
  11036. if (this._rescalePostProcess) {
  11037. this._rescalePostProcess.dispose();
  11038. }
  11039. // Release scenes
  11040. while (this.scenes.length) {
  11041. this.scenes[0].dispose();
  11042. }
  11043. // Release audio engine
  11044. if (Engine.audioEngine) {
  11045. Engine.audioEngine.dispose();
  11046. }
  11047. // Release effects
  11048. this.releaseEffects();
  11049. // Unbind
  11050. this.unbindAllAttributes();
  11051. if (this._dummyFramebuffer) {
  11052. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11053. }
  11054. this._gl = null;
  11055. //WebVR
  11056. this.disableVR();
  11057. // Events
  11058. window.removeEventListener("blur", this._onBlur);
  11059. window.removeEventListener("focus", this._onFocus);
  11060. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11061. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11062. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11063. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11064. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11065. if (!this._doNotHandleContextLost) {
  11066. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11067. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11068. }
  11069. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11070. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11071. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11072. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11073. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11074. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11075. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11076. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11077. // Remove from Instances
  11078. var index = Engine.Instances.indexOf(this);
  11079. if (index >= 0) {
  11080. Engine.Instances.splice(index, 1);
  11081. }
  11082. this._workingCanvas = null;
  11083. this._workingContext = null;
  11084. this._currentBufferPointers = null;
  11085. this._renderingCanvas = null;
  11086. this._currentProgram = null;
  11087. this.onResizeObservable.clear();
  11088. this.onCanvasBlurObservable.clear();
  11089. this.onCanvasFocusObservable.clear();
  11090. this.onCanvasPointerOutObservable.clear();
  11091. BABYLON.Effect.ResetCache();
  11092. };
  11093. // Loading screen
  11094. Engine.prototype.displayLoadingUI = function () {
  11095. var loadingScreen = this.loadingScreen;
  11096. if (loadingScreen) {
  11097. loadingScreen.displayLoadingUI();
  11098. }
  11099. };
  11100. Engine.prototype.hideLoadingUI = function () {
  11101. var loadingScreen = this.loadingScreen;
  11102. if (loadingScreen) {
  11103. loadingScreen.hideLoadingUI();
  11104. }
  11105. };
  11106. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11107. get: function () {
  11108. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  11109. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11110. return this._loadingScreen;
  11111. },
  11112. set: function (loadingScreen) {
  11113. this._loadingScreen = loadingScreen;
  11114. },
  11115. enumerable: true,
  11116. configurable: true
  11117. });
  11118. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11119. set: function (text) {
  11120. this.loadingScreen.loadingUIText = text;
  11121. },
  11122. enumerable: true,
  11123. configurable: true
  11124. });
  11125. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11126. set: function (color) {
  11127. this.loadingScreen.loadingUIBackgroundColor = color;
  11128. },
  11129. enumerable: true,
  11130. configurable: true
  11131. });
  11132. Engine.prototype.attachContextLostEvent = function (callback) {
  11133. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11134. };
  11135. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11136. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11137. };
  11138. Engine.prototype.getVertexShaderSource = function (program) {
  11139. var shaders = this._gl.getAttachedShaders(program);
  11140. return this._gl.getShaderSource(shaders[0]);
  11141. };
  11142. Engine.prototype.getFragmentShaderSource = function (program) {
  11143. var shaders = this._gl.getAttachedShaders(program);
  11144. return this._gl.getShaderSource(shaders[1]);
  11145. };
  11146. Engine.prototype.getError = function () {
  11147. return this._gl.getError();
  11148. };
  11149. // FPS
  11150. Engine.prototype.getFps = function () {
  11151. return this._fps;
  11152. };
  11153. Engine.prototype.getDeltaTime = function () {
  11154. return this._deltaTime;
  11155. };
  11156. Engine.prototype._measureFps = function () {
  11157. this._performanceMonitor.sampleFrame();
  11158. this._fps = this._performanceMonitor.averageFPS;
  11159. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11160. };
  11161. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11162. if (faceIndex === void 0) { faceIndex = -1; }
  11163. var gl = this._gl;
  11164. if (!this._dummyFramebuffer) {
  11165. this._dummyFramebuffer = gl.createFramebuffer();
  11166. }
  11167. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11168. if (faceIndex > -1) {
  11169. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11170. }
  11171. else {
  11172. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11173. }
  11174. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11175. var buffer;
  11176. switch (readType) {
  11177. case gl.UNSIGNED_BYTE:
  11178. buffer = new Uint8Array(4 * width * height);
  11179. readType = gl.UNSIGNED_BYTE;
  11180. break;
  11181. default:
  11182. buffer = new Float32Array(4 * width * height);
  11183. readType = gl.FLOAT;
  11184. break;
  11185. }
  11186. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11187. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11188. return buffer;
  11189. };
  11190. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11191. if (this._webGLVersion > 1) {
  11192. return this._caps.colorBufferFloat;
  11193. }
  11194. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11195. };
  11196. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11197. if (this._webGLVersion > 1) {
  11198. return this._caps.colorBufferFloat;
  11199. }
  11200. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11201. };
  11202. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11203. Engine.prototype._canRenderToFramebuffer = function (type) {
  11204. var gl = this._gl;
  11205. //clear existing errors
  11206. while (gl.getError() !== gl.NO_ERROR) { }
  11207. var successful = true;
  11208. var texture = gl.createTexture();
  11209. gl.bindTexture(gl.TEXTURE_2D, texture);
  11210. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11211. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11212. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11213. var fb = gl.createFramebuffer();
  11214. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11215. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11216. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11217. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11218. successful = successful && (gl.getError() === gl.NO_ERROR);
  11219. //try render by clearing frame buffer's color buffer
  11220. if (successful) {
  11221. gl.clear(gl.COLOR_BUFFER_BIT);
  11222. successful = successful && (gl.getError() === gl.NO_ERROR);
  11223. }
  11224. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11225. if (successful) {
  11226. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11227. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11228. var readFormat = gl.RGBA;
  11229. var readType = gl.UNSIGNED_BYTE;
  11230. var buffer = new Uint8Array(4);
  11231. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11232. successful = successful && (gl.getError() === gl.NO_ERROR);
  11233. }
  11234. //clean up
  11235. gl.deleteTexture(texture);
  11236. gl.deleteFramebuffer(fb);
  11237. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11238. //clear accumulated errors
  11239. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11240. return successful;
  11241. };
  11242. Engine.prototype._getWebGLTextureType = function (type) {
  11243. if (type === Engine.TEXTURETYPE_FLOAT) {
  11244. return this._gl.FLOAT;
  11245. }
  11246. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11247. // Add Half Float Constant.
  11248. return this._gl.HALF_FLOAT_OES;
  11249. }
  11250. return this._gl.UNSIGNED_BYTE;
  11251. };
  11252. ;
  11253. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11254. if (this._webGLVersion === 1) {
  11255. return this._gl.RGBA;
  11256. }
  11257. if (type === Engine.TEXTURETYPE_FLOAT) {
  11258. return this._gl.RGBA32F;
  11259. }
  11260. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11261. return this._gl.RGBA16F;
  11262. }
  11263. return this._gl.RGBA;
  11264. };
  11265. ;
  11266. Engine.prototype.createQuery = function () {
  11267. return this._gl.createQuery();
  11268. };
  11269. Engine.prototype.deleteQuery = function (query) {
  11270. this._gl.deleteQuery(query);
  11271. return this;
  11272. };
  11273. Engine.prototype.isQueryResultAvailable = function (query) {
  11274. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11275. };
  11276. Engine.prototype.getQueryResult = function (query) {
  11277. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11278. };
  11279. Engine.prototype.beginQuery = function (algorithmType, query) {
  11280. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11281. this._gl.beginQuery(glAlgorithm, query);
  11282. };
  11283. Engine.prototype.endQuery = function (algorithmType) {
  11284. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11285. this._gl.endQuery(glAlgorithm);
  11286. return this;
  11287. };
  11288. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11289. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11290. };
  11291. // Statics
  11292. Engine.isSupported = function () {
  11293. try {
  11294. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11295. if (navigator.isCocoonJS) {
  11296. return true;
  11297. }
  11298. var tempcanvas = document.createElement("canvas");
  11299. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11300. return gl != null && !!window.WebGLRenderingContext;
  11301. }
  11302. catch (e) {
  11303. return false;
  11304. }
  11305. };
  11306. Engine.Instances = new Array();
  11307. // Const statics
  11308. Engine._ALPHA_DISABLE = 0;
  11309. Engine._ALPHA_ADD = 1;
  11310. Engine._ALPHA_COMBINE = 2;
  11311. Engine._ALPHA_SUBTRACT = 3;
  11312. Engine._ALPHA_MULTIPLY = 4;
  11313. Engine._ALPHA_MAXIMIZED = 5;
  11314. Engine._ALPHA_ONEONE = 6;
  11315. Engine._ALPHA_PREMULTIPLIED = 7;
  11316. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11317. Engine._ALPHA_INTERPOLATE = 9;
  11318. Engine._ALPHA_SCREENMODE = 10;
  11319. Engine._DELAYLOADSTATE_NONE = 0;
  11320. Engine._DELAYLOADSTATE_LOADED = 1;
  11321. Engine._DELAYLOADSTATE_LOADING = 2;
  11322. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11323. Engine._TEXTUREFORMAT_ALPHA = 0;
  11324. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11325. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11326. Engine._TEXTUREFORMAT_RGB = 4;
  11327. Engine._TEXTUREFORMAT_RGBA = 5;
  11328. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11329. Engine._TEXTURETYPE_FLOAT = 1;
  11330. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11331. // Depht or Stencil test Constants.
  11332. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11333. 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.
  11334. 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.
  11335. 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.
  11336. 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.
  11337. 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.
  11338. 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.
  11339. 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.
  11340. // Stencil Actions Constants.
  11341. Engine._KEEP = 0x1E00;
  11342. Engine._REPLACE = 0x1E01;
  11343. Engine._INCR = 0x1E02;
  11344. Engine._DECR = 0x1E03;
  11345. Engine._INVERT = 0x150A;
  11346. Engine._INCR_WRAP = 0x8507;
  11347. Engine._DECR_WRAP = 0x8508;
  11348. // Texture rescaling mode
  11349. Engine._SCALEMODE_FLOOR = 1;
  11350. Engine._SCALEMODE_NEAREST = 2;
  11351. Engine._SCALEMODE_CEILING = 3;
  11352. // Updatable statics so stick with vars here
  11353. Engine.CollisionsEpsilon = 0.001;
  11354. Engine.CodeRepository = "src/";
  11355. Engine.ShadersRepository = "src/Shaders/";
  11356. return Engine;
  11357. }());
  11358. BABYLON.Engine = Engine;
  11359. })(BABYLON || (BABYLON = {}));
  11360. //# sourceMappingURL=babylon.engine.js.map
  11361. /// <reference path="Tools\babylon.decorators.ts" />
  11362. var BABYLON;
  11363. (function (BABYLON) {
  11364. /**
  11365. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11366. */
  11367. var Node = (function () {
  11368. /**
  11369. * @constructor
  11370. * @param {string} name - the name and id to be given to this node
  11371. * @param {BABYLON.Scene} the scene this node will be added to
  11372. */
  11373. function Node(name, scene) {
  11374. this.state = "";
  11375. this.metadata = null;
  11376. this.doNotSerialize = false;
  11377. this.animations = new Array();
  11378. this._ranges = {};
  11379. this._childrenFlag = -1;
  11380. this._isEnabled = true;
  11381. this._isReady = true;
  11382. this._currentRenderId = -1;
  11383. this._parentRenderId = -1;
  11384. /**
  11385. * An event triggered when the mesh is disposed.
  11386. * @type {BABYLON.Observable}
  11387. */
  11388. this.onDisposeObservable = new BABYLON.Observable();
  11389. // Behaviors
  11390. this._behaviors = new Array();
  11391. this.name = name;
  11392. this.id = name;
  11393. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11394. this._initCache();
  11395. }
  11396. Object.defineProperty(Node.prototype, "parent", {
  11397. get: function () {
  11398. return this._parentNode;
  11399. },
  11400. set: function (parent) {
  11401. if (this._parentNode === parent) {
  11402. return;
  11403. }
  11404. if (this._parentNode) {
  11405. var index = this._parentNode._children.indexOf(this);
  11406. if (index !== -1) {
  11407. this._parentNode._children.splice(index, 1);
  11408. }
  11409. }
  11410. this._parentNode = parent;
  11411. if (this._parentNode) {
  11412. if (!this._parentNode._children) {
  11413. this._parentNode._children = new Array();
  11414. }
  11415. this._parentNode._children.push(this);
  11416. }
  11417. },
  11418. enumerable: true,
  11419. configurable: true
  11420. });
  11421. Node.prototype.getClassName = function () {
  11422. return "Node";
  11423. };
  11424. Object.defineProperty(Node.prototype, "onDispose", {
  11425. set: function (callback) {
  11426. if (this._onDisposeObserver) {
  11427. this.onDisposeObservable.remove(this._onDisposeObserver);
  11428. }
  11429. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11430. },
  11431. enumerable: true,
  11432. configurable: true
  11433. });
  11434. Node.prototype.getScene = function () {
  11435. return this._scene;
  11436. };
  11437. Node.prototype.getEngine = function () {
  11438. return this._scene.getEngine();
  11439. };
  11440. Node.prototype.addBehavior = function (behavior) {
  11441. var index = this._behaviors.indexOf(behavior);
  11442. if (index !== -1) {
  11443. return;
  11444. }
  11445. behavior.attach(this);
  11446. this._behaviors.push(behavior);
  11447. return this;
  11448. };
  11449. Node.prototype.removeBehavior = function (behavior) {
  11450. var index = this._behaviors.indexOf(behavior);
  11451. if (index === -1) {
  11452. return;
  11453. }
  11454. this._behaviors[index].detach();
  11455. this._behaviors.splice(index, 1);
  11456. return this;
  11457. };
  11458. Object.defineProperty(Node.prototype, "behaviors", {
  11459. get: function () {
  11460. return this._behaviors;
  11461. },
  11462. enumerable: true,
  11463. configurable: true
  11464. });
  11465. Node.prototype.getBehaviorByName = function (name) {
  11466. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11467. var behavior = _a[_i];
  11468. if (behavior.name === name) {
  11469. return behavior;
  11470. }
  11471. }
  11472. return null;
  11473. };
  11474. // override it in derived class
  11475. Node.prototype.getWorldMatrix = function () {
  11476. return BABYLON.Matrix.Identity();
  11477. };
  11478. // override it in derived class if you add new variables to the cache
  11479. // and call the parent class method
  11480. Node.prototype._initCache = function () {
  11481. this._cache = {};
  11482. this._cache.parent = undefined;
  11483. };
  11484. Node.prototype.updateCache = function (force) {
  11485. if (!force && this.isSynchronized())
  11486. return;
  11487. this._cache.parent = this.parent;
  11488. this._updateCache();
  11489. };
  11490. // override it in derived class if you add new variables to the cache
  11491. // and call the parent class method if !ignoreParentClass
  11492. Node.prototype._updateCache = function (ignoreParentClass) {
  11493. };
  11494. // override it in derived class if you add new variables to the cache
  11495. Node.prototype._isSynchronized = function () {
  11496. return true;
  11497. };
  11498. Node.prototype._markSyncedWithParent = function () {
  11499. this._parentRenderId = this.parent._currentRenderId;
  11500. };
  11501. Node.prototype.isSynchronizedWithParent = function () {
  11502. if (!this.parent) {
  11503. return true;
  11504. }
  11505. if (this._parentRenderId !== this.parent._currentRenderId) {
  11506. return false;
  11507. }
  11508. return this.parent.isSynchronized();
  11509. };
  11510. Node.prototype.isSynchronized = function (updateCache) {
  11511. var check = this.hasNewParent();
  11512. check = check || !this.isSynchronizedWithParent();
  11513. check = check || !this._isSynchronized();
  11514. if (updateCache)
  11515. this.updateCache(true);
  11516. return !check;
  11517. };
  11518. Node.prototype.hasNewParent = function (update) {
  11519. if (this._cache.parent === this.parent)
  11520. return false;
  11521. if (update)
  11522. this._cache.parent = this.parent;
  11523. return true;
  11524. };
  11525. /**
  11526. * Is this node ready to be used/rendered
  11527. * @return {boolean} is it ready
  11528. */
  11529. Node.prototype.isReady = function () {
  11530. return this._isReady;
  11531. };
  11532. /**
  11533. * Is this node enabled.
  11534. * If the node has a parent and is enabled, the parent will be inspected as well.
  11535. * @return {boolean} whether this node (and its parent) is enabled.
  11536. * @see setEnabled
  11537. */
  11538. Node.prototype.isEnabled = function () {
  11539. if (!this._isEnabled) {
  11540. return false;
  11541. }
  11542. if (this.parent) {
  11543. return this.parent.isEnabled();
  11544. }
  11545. return true;
  11546. };
  11547. /**
  11548. * Set the enabled state of this node.
  11549. * @param {boolean} value - the new enabled state
  11550. * @see isEnabled
  11551. */
  11552. Node.prototype.setEnabled = function (value) {
  11553. this._isEnabled = value;
  11554. };
  11555. /**
  11556. * Is this node a descendant of the given node.
  11557. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11558. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11559. * @see parent
  11560. */
  11561. Node.prototype.isDescendantOf = function (ancestor) {
  11562. if (this.parent) {
  11563. if (this.parent === ancestor) {
  11564. return true;
  11565. }
  11566. return this.parent.isDescendantOf(ancestor);
  11567. }
  11568. return false;
  11569. };
  11570. /**
  11571. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11572. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11573. * @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.
  11574. * @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.
  11575. */
  11576. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11577. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11578. if (!this._children) {
  11579. return;
  11580. }
  11581. for (var index = 0; index < this._children.length; index++) {
  11582. var item = this._children[index];
  11583. if (!predicate || predicate(item)) {
  11584. results.push(item);
  11585. }
  11586. if (!directDescendantsOnly) {
  11587. item._getDescendants(results, false, predicate);
  11588. }
  11589. }
  11590. };
  11591. /**
  11592. * Will return all nodes that have this node as ascendant.
  11593. * @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.
  11594. * @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.
  11595. * @return {BABYLON.Node[]} all children nodes of all types.
  11596. */
  11597. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11598. var results = [];
  11599. this._getDescendants(results, directDescendantsOnly, predicate);
  11600. return results;
  11601. };
  11602. /**
  11603. * Get all child-meshes of this node.
  11604. */
  11605. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11606. var results = [];
  11607. this._getDescendants(results, directDecendantsOnly, function (node) {
  11608. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11609. });
  11610. return results;
  11611. };
  11612. /**
  11613. * Get all direct children of this node.
  11614. */
  11615. Node.prototype.getChildren = function (predicate) {
  11616. return this.getDescendants(true, predicate);
  11617. };
  11618. Node.prototype._setReady = function (state) {
  11619. if (state === this._isReady) {
  11620. return;
  11621. }
  11622. if (!state) {
  11623. this._isReady = false;
  11624. return;
  11625. }
  11626. this._isReady = true;
  11627. if (this.onReady) {
  11628. this.onReady(this);
  11629. }
  11630. };
  11631. Node.prototype.getAnimationByName = function (name) {
  11632. for (var i = 0; i < this.animations.length; i++) {
  11633. var animation = this.animations[i];
  11634. if (animation.name === name) {
  11635. return animation;
  11636. }
  11637. }
  11638. return null;
  11639. };
  11640. Node.prototype.createAnimationRange = function (name, from, to) {
  11641. // check name not already in use
  11642. if (!this._ranges[name]) {
  11643. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11644. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11645. if (this.animations[i]) {
  11646. this.animations[i].createRange(name, from, to);
  11647. }
  11648. }
  11649. }
  11650. };
  11651. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11652. if (deleteFrames === void 0) { deleteFrames = true; }
  11653. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11654. if (this.animations[i]) {
  11655. this.animations[i].deleteRange(name, deleteFrames);
  11656. }
  11657. }
  11658. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11659. };
  11660. Node.prototype.getAnimationRange = function (name) {
  11661. return this._ranges[name];
  11662. };
  11663. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11664. var range = this.getAnimationRange(name);
  11665. if (!range) {
  11666. return null;
  11667. }
  11668. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11669. };
  11670. Node.prototype.serializeAnimationRanges = function () {
  11671. var serializationRanges = [];
  11672. for (var name in this._ranges) {
  11673. var range = {};
  11674. range.name = name;
  11675. range.from = this._ranges[name].from;
  11676. range.to = this._ranges[name].to;
  11677. serializationRanges.push(range);
  11678. }
  11679. return serializationRanges;
  11680. };
  11681. Node.prototype.dispose = function () {
  11682. this.parent = null;
  11683. // Callback
  11684. this.onDisposeObservable.notifyObservers(this);
  11685. this.onDisposeObservable.clear();
  11686. // Behaviors
  11687. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11688. var behavior = _a[_i];
  11689. behavior.detach();
  11690. }
  11691. this._behaviors = [];
  11692. };
  11693. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11694. if (parsedNode.ranges) {
  11695. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11696. var data = parsedNode.ranges[index];
  11697. node.createAnimationRange(data.name, data.from, data.to);
  11698. }
  11699. }
  11700. };
  11701. __decorate([
  11702. BABYLON.serialize()
  11703. ], Node.prototype, "name", void 0);
  11704. __decorate([
  11705. BABYLON.serialize()
  11706. ], Node.prototype, "id", void 0);
  11707. __decorate([
  11708. BABYLON.serialize()
  11709. ], Node.prototype, "uniqueId", void 0);
  11710. __decorate([
  11711. BABYLON.serialize()
  11712. ], Node.prototype, "state", void 0);
  11713. __decorate([
  11714. BABYLON.serialize()
  11715. ], Node.prototype, "metadata", void 0);
  11716. return Node;
  11717. }());
  11718. BABYLON.Node = Node;
  11719. })(BABYLON || (BABYLON = {}));
  11720. //# sourceMappingURL=babylon.node.js.map
  11721. var BABYLON;
  11722. (function (BABYLON) {
  11723. var BoundingSphere = (function () {
  11724. function BoundingSphere(minimum, maximum) {
  11725. this.minimum = minimum;
  11726. this.maximum = maximum;
  11727. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11728. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11729. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11730. this.radius = distance * 0.5;
  11731. this.centerWorld = BABYLON.Vector3.Zero();
  11732. this._update(BABYLON.Matrix.Identity());
  11733. }
  11734. // Methods
  11735. BoundingSphere.prototype._update = function (world) {
  11736. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11737. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11738. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11739. };
  11740. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11741. for (var i = 0; i < 6; i++) {
  11742. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11743. return false;
  11744. }
  11745. return true;
  11746. };
  11747. BoundingSphere.prototype.intersectsPoint = function (point) {
  11748. var x = this.centerWorld.x - point.x;
  11749. var y = this.centerWorld.y - point.y;
  11750. var z = this.centerWorld.z - point.z;
  11751. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11752. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11753. return false;
  11754. return true;
  11755. };
  11756. // Statics
  11757. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11758. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11759. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11760. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11761. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11762. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11763. return false;
  11764. return true;
  11765. };
  11766. return BoundingSphere;
  11767. }());
  11768. BABYLON.BoundingSphere = BoundingSphere;
  11769. })(BABYLON || (BABYLON = {}));
  11770. //# sourceMappingURL=babylon.boundingSphere.js.map
  11771. var BABYLON;
  11772. (function (BABYLON) {
  11773. var BoundingBox = (function () {
  11774. function BoundingBox(minimum, maximum) {
  11775. this.minimum = minimum;
  11776. this.maximum = maximum;
  11777. this.vectors = new Array();
  11778. this.vectorsWorld = new Array();
  11779. // Bounding vectors
  11780. this.vectors.push(this.minimum.clone());
  11781. this.vectors.push(this.maximum.clone());
  11782. this.vectors.push(this.minimum.clone());
  11783. this.vectors[2].x = this.maximum.x;
  11784. this.vectors.push(this.minimum.clone());
  11785. this.vectors[3].y = this.maximum.y;
  11786. this.vectors.push(this.minimum.clone());
  11787. this.vectors[4].z = this.maximum.z;
  11788. this.vectors.push(this.maximum.clone());
  11789. this.vectors[5].z = this.minimum.z;
  11790. this.vectors.push(this.maximum.clone());
  11791. this.vectors[6].x = this.minimum.x;
  11792. this.vectors.push(this.maximum.clone());
  11793. this.vectors[7].y = this.minimum.y;
  11794. // OBB
  11795. this.center = this.maximum.add(this.minimum).scale(0.5);
  11796. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11797. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11798. // World
  11799. for (var index = 0; index < this.vectors.length; index++) {
  11800. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11801. }
  11802. this.minimumWorld = BABYLON.Vector3.Zero();
  11803. this.maximumWorld = BABYLON.Vector3.Zero();
  11804. this.centerWorld = BABYLON.Vector3.Zero();
  11805. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11806. this._update(BABYLON.Matrix.Identity());
  11807. }
  11808. // Methods
  11809. BoundingBox.prototype.getWorldMatrix = function () {
  11810. return this._worldMatrix;
  11811. };
  11812. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11813. this._worldMatrix.copyFrom(matrix);
  11814. return this;
  11815. };
  11816. BoundingBox.prototype._update = function (world) {
  11817. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11818. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11819. for (var index = 0; index < this.vectors.length; index++) {
  11820. var v = this.vectorsWorld[index];
  11821. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11822. if (v.x < this.minimumWorld.x)
  11823. this.minimumWorld.x = v.x;
  11824. if (v.y < this.minimumWorld.y)
  11825. this.minimumWorld.y = v.y;
  11826. if (v.z < this.minimumWorld.z)
  11827. this.minimumWorld.z = v.z;
  11828. if (v.x > this.maximumWorld.x)
  11829. this.maximumWorld.x = v.x;
  11830. if (v.y > this.maximumWorld.y)
  11831. this.maximumWorld.y = v.y;
  11832. if (v.z > this.maximumWorld.z)
  11833. this.maximumWorld.z = v.z;
  11834. }
  11835. // Extend
  11836. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11837. this.extendSizeWorld.scaleInPlace(0.5);
  11838. // OBB
  11839. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11840. this.centerWorld.scaleInPlace(0.5);
  11841. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11842. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11843. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11844. this._worldMatrix = world;
  11845. };
  11846. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11847. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11848. };
  11849. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11850. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11851. };
  11852. BoundingBox.prototype.intersectsPoint = function (point) {
  11853. var delta = -BABYLON.Epsilon;
  11854. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11855. return false;
  11856. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11857. return false;
  11858. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11859. return false;
  11860. return true;
  11861. };
  11862. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11863. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11864. };
  11865. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11866. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11867. return false;
  11868. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11869. return false;
  11870. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11871. return false;
  11872. return true;
  11873. };
  11874. // Statics
  11875. BoundingBox.Intersects = function (box0, box1) {
  11876. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11877. return false;
  11878. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11879. return false;
  11880. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11881. return false;
  11882. return true;
  11883. };
  11884. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11885. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11886. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11887. return (num <= (sphereRadius * sphereRadius));
  11888. };
  11889. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11890. for (var p = 0; p < 6; p++) {
  11891. for (var i = 0; i < 8; i++) {
  11892. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11893. return false;
  11894. }
  11895. }
  11896. }
  11897. return true;
  11898. };
  11899. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11900. for (var p = 0; p < 6; p++) {
  11901. var inCount = 8;
  11902. for (var i = 0; i < 8; i++) {
  11903. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11904. --inCount;
  11905. }
  11906. else {
  11907. break;
  11908. }
  11909. }
  11910. if (inCount === 0)
  11911. return false;
  11912. }
  11913. return true;
  11914. };
  11915. return BoundingBox;
  11916. }());
  11917. BABYLON.BoundingBox = BoundingBox;
  11918. })(BABYLON || (BABYLON = {}));
  11919. //# sourceMappingURL=babylon.boundingBox.js.map
  11920. var BABYLON;
  11921. (function (BABYLON) {
  11922. var computeBoxExtents = function (axis, box) {
  11923. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11924. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11925. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11926. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11927. var r = r0 + r1 + r2;
  11928. return {
  11929. min: p - r,
  11930. max: p + r
  11931. };
  11932. };
  11933. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11934. var axisOverlap = function (axis, box0, box1) {
  11935. var result0 = computeBoxExtents(axis, box0);
  11936. var result1 = computeBoxExtents(axis, box1);
  11937. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11938. };
  11939. var BoundingInfo = (function () {
  11940. function BoundingInfo(minimum, maximum) {
  11941. this.minimum = minimum;
  11942. this.maximum = maximum;
  11943. this._isLocked = false;
  11944. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11945. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11946. }
  11947. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11948. get: function () {
  11949. return this._isLocked;
  11950. },
  11951. set: function (value) {
  11952. this._isLocked = value;
  11953. },
  11954. enumerable: true,
  11955. configurable: true
  11956. });
  11957. // Methods
  11958. BoundingInfo.prototype.update = function (world) {
  11959. if (this._isLocked) {
  11960. return;
  11961. }
  11962. this.boundingBox._update(world);
  11963. this.boundingSphere._update(world);
  11964. };
  11965. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11966. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11967. return false;
  11968. return this.boundingBox.isInFrustum(frustumPlanes);
  11969. };
  11970. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  11971. /**
  11972. * Gets the world distance between the min and max points of the bounding box
  11973. */
  11974. get: function () {
  11975. var boundingBox = this.boundingBox;
  11976. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  11977. return size.length();
  11978. },
  11979. enumerable: true,
  11980. configurable: true
  11981. });
  11982. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11983. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11984. };
  11985. BoundingInfo.prototype._checkCollision = function (collider) {
  11986. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11987. };
  11988. BoundingInfo.prototype.intersectsPoint = function (point) {
  11989. if (!this.boundingSphere.centerWorld) {
  11990. return false;
  11991. }
  11992. if (!this.boundingSphere.intersectsPoint(point)) {
  11993. return false;
  11994. }
  11995. if (!this.boundingBox.intersectsPoint(point)) {
  11996. return false;
  11997. }
  11998. return true;
  11999. };
  12000. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12001. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12002. return false;
  12003. }
  12004. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12005. return false;
  12006. }
  12007. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12008. return false;
  12009. }
  12010. if (!precise) {
  12011. return true;
  12012. }
  12013. var box0 = this.boundingBox;
  12014. var box1 = boundingInfo.boundingBox;
  12015. if (!axisOverlap(box0.directions[0], box0, box1))
  12016. return false;
  12017. if (!axisOverlap(box0.directions[1], box0, box1))
  12018. return false;
  12019. if (!axisOverlap(box0.directions[2], box0, box1))
  12020. return false;
  12021. if (!axisOverlap(box1.directions[0], box0, box1))
  12022. return false;
  12023. if (!axisOverlap(box1.directions[1], box0, box1))
  12024. return false;
  12025. if (!axisOverlap(box1.directions[2], box0, box1))
  12026. return false;
  12027. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12028. return false;
  12029. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12030. return false;
  12031. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12032. return false;
  12033. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12034. return false;
  12035. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12036. return false;
  12037. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12038. return false;
  12039. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12040. return false;
  12041. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12042. return false;
  12043. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12044. return false;
  12045. return true;
  12046. };
  12047. return BoundingInfo;
  12048. }());
  12049. BABYLON.BoundingInfo = BoundingInfo;
  12050. })(BABYLON || (BABYLON = {}));
  12051. //# sourceMappingURL=babylon.boundingInfo.js.map
  12052. var BABYLON;
  12053. (function (BABYLON) {
  12054. var AbstractMesh = (function (_super) {
  12055. __extends(AbstractMesh, _super);
  12056. // Constructor
  12057. function AbstractMesh(name, scene) {
  12058. var _this = _super.call(this, name, scene) || this;
  12059. _this._facetNb = 0; // facet number
  12060. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12061. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12062. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12063. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12064. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12065. _this._subDiv = {
  12066. max: 1,
  12067. X: 1,
  12068. Y: 1,
  12069. Z: 1
  12070. };
  12071. // Events
  12072. /**
  12073. * An event triggered when this mesh collides with another one
  12074. * @type {BABYLON.Observable}
  12075. */
  12076. _this.onCollideObservable = new BABYLON.Observable();
  12077. /**
  12078. * An event triggered when the collision's position changes
  12079. * @type {BABYLON.Observable}
  12080. */
  12081. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12082. /**
  12083. * An event triggered after the world matrix is updated
  12084. * @type {BABYLON.Observable}
  12085. */
  12086. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12087. /**
  12088. * An event triggered when material is changed
  12089. * @type {BABYLON.Observable}
  12090. */
  12091. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12092. // Properties
  12093. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12094. _this.position = BABYLON.Vector3.Zero();
  12095. /**
  12096. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12097. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12098. * or
  12099. * 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.
  12100. * for more info check WebGl documentations
  12101. */
  12102. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12103. /**
  12104. * 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:
  12105. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12106. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12107. * 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.
  12108. */
  12109. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12110. /**
  12111. * 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.
  12112. * The default value is -1 which means don't break the query and wait till the result.
  12113. */
  12114. _this.occlusionRetryCount = -1;
  12115. _this._occlusionInternalRetryCounter = 0;
  12116. _this._isOccluded = false;
  12117. _this._isOcclusionQueryInProgress = false;
  12118. _this._rotation = BABYLON.Vector3.Zero();
  12119. _this._scaling = BABYLON.Vector3.One();
  12120. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12121. _this.visibility = 1.0;
  12122. _this.alphaIndex = Number.MAX_VALUE;
  12123. _this.infiniteDistance = false;
  12124. _this.isVisible = true;
  12125. _this.isPickable = true;
  12126. _this.showBoundingBox = false;
  12127. _this.showSubMeshesBoundingBox = false;
  12128. _this.isBlocker = false;
  12129. _this.enablePointerMoveEvents = false;
  12130. _this.renderingGroupId = 0;
  12131. _this._receiveShadows = false;
  12132. _this.renderOutline = false;
  12133. _this.outlineColor = BABYLON.Color3.Red();
  12134. _this.outlineWidth = 0.02;
  12135. _this.renderOverlay = false;
  12136. _this.overlayColor = BABYLON.Color3.Red();
  12137. _this.overlayAlpha = 0.5;
  12138. _this._hasVertexAlpha = false;
  12139. _this._useVertexColors = true;
  12140. _this._computeBonesUsingShaders = true;
  12141. _this._numBoneInfluencers = 4;
  12142. _this._applyFog = true;
  12143. _this.scalingDeterminant = 1;
  12144. _this.useOctreeForRenderingSelection = true;
  12145. _this.useOctreeForPicking = true;
  12146. _this.useOctreeForCollisions = true;
  12147. _this._layerMask = 0x0FFFFFFF;
  12148. /**
  12149. * True if the mesh must be rendered in any case.
  12150. */
  12151. _this.alwaysSelectAsActiveMesh = false;
  12152. // Collisions
  12153. _this._checkCollisions = false;
  12154. _this._collisionMask = -1;
  12155. _this._collisionGroup = -1;
  12156. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12157. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12158. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12159. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12160. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12161. // Edges
  12162. _this.edgesWidth = 1;
  12163. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12164. // Cache
  12165. _this._localWorld = BABYLON.Matrix.Zero();
  12166. _this._worldMatrix = BABYLON.Matrix.Zero();
  12167. _this._absolutePosition = BABYLON.Vector3.Zero();
  12168. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12169. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12170. _this._isDirty = false;
  12171. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12172. _this._isDisposed = false;
  12173. _this._renderId = 0;
  12174. _this._intersectionsInProgress = new Array();
  12175. _this._isWorldMatrixFrozen = false;
  12176. _this._unIndexed = false;
  12177. _this._lightSources = new Array();
  12178. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12179. if (collidedMesh === void 0) { collidedMesh = null; }
  12180. //TODO move this to the collision coordinator!
  12181. if (_this.getScene().workerCollisions)
  12182. newPosition.multiplyInPlace(_this._collider.radius);
  12183. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12184. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12185. _this.position.addInPlace(_this._diffPositionForCollisions);
  12186. }
  12187. if (collidedMesh) {
  12188. _this.onCollideObservable.notifyObservers(collidedMesh);
  12189. }
  12190. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12191. };
  12192. _this.getScene().addMesh(_this);
  12193. _this._resyncLightSources();
  12194. return _this;
  12195. }
  12196. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12197. get: function () {
  12198. return AbstractMesh._BILLBOARDMODE_NONE;
  12199. },
  12200. enumerable: true,
  12201. configurable: true
  12202. });
  12203. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12204. get: function () {
  12205. return AbstractMesh._BILLBOARDMODE_X;
  12206. },
  12207. enumerable: true,
  12208. configurable: true
  12209. });
  12210. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12211. get: function () {
  12212. return AbstractMesh._BILLBOARDMODE_Y;
  12213. },
  12214. enumerable: true,
  12215. configurable: true
  12216. });
  12217. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12218. get: function () {
  12219. return AbstractMesh._BILLBOARDMODE_Z;
  12220. },
  12221. enumerable: true,
  12222. configurable: true
  12223. });
  12224. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12225. get: function () {
  12226. return AbstractMesh._BILLBOARDMODE_ALL;
  12227. },
  12228. enumerable: true,
  12229. configurable: true
  12230. });
  12231. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12232. /**
  12233. * Read-only : the number of facets in the mesh
  12234. */
  12235. get: function () {
  12236. return this._facetNb;
  12237. },
  12238. enumerable: true,
  12239. configurable: true
  12240. });
  12241. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12242. /**
  12243. * The number (integer) of subdivisions per axis in the partioning space
  12244. */
  12245. get: function () {
  12246. return this._partitioningSubdivisions;
  12247. },
  12248. set: function (nb) {
  12249. this._partitioningSubdivisions = nb;
  12250. },
  12251. enumerable: true,
  12252. configurable: true
  12253. });
  12254. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12255. /**
  12256. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12257. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12258. */
  12259. get: function () {
  12260. return this._partitioningBBoxRatio;
  12261. },
  12262. set: function (ratio) {
  12263. this._partitioningBBoxRatio = ratio;
  12264. },
  12265. enumerable: true,
  12266. configurable: true
  12267. });
  12268. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12269. /**
  12270. * Read-only boolean : is the feature facetData enabled ?
  12271. */
  12272. get: function () {
  12273. return this._facetDataEnabled;
  12274. },
  12275. enumerable: true,
  12276. configurable: true
  12277. });
  12278. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12279. set: function (callback) {
  12280. if (this._onCollideObserver) {
  12281. this.onCollideObservable.remove(this._onCollideObserver);
  12282. }
  12283. this._onCollideObserver = this.onCollideObservable.add(callback);
  12284. },
  12285. enumerable: true,
  12286. configurable: true
  12287. });
  12288. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12289. set: function (callback) {
  12290. if (this._onCollisionPositionChangeObserver) {
  12291. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12292. }
  12293. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12294. },
  12295. enumerable: true,
  12296. configurable: true
  12297. });
  12298. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12299. /**
  12300. * 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.
  12301. */
  12302. get: function () {
  12303. return this._isOccluded;
  12304. },
  12305. set: function (value) {
  12306. this._isOccluded = value;
  12307. },
  12308. enumerable: true,
  12309. configurable: true
  12310. });
  12311. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12312. /**
  12313. * Flag to check the progress status of the query
  12314. */
  12315. get: function () {
  12316. return this._isOcclusionQueryInProgress;
  12317. },
  12318. enumerable: true,
  12319. configurable: true
  12320. });
  12321. Object.defineProperty(AbstractMesh.prototype, "material", {
  12322. get: function () {
  12323. return this._material;
  12324. },
  12325. set: function (value) {
  12326. if (this._material === value) {
  12327. return;
  12328. }
  12329. this._material = value;
  12330. if (this.onMaterialChangedObservable.hasObservers) {
  12331. this.onMaterialChangedObservable.notifyObservers(this);
  12332. }
  12333. if (!this.subMeshes) {
  12334. return;
  12335. }
  12336. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12337. var subMesh = _a[_i];
  12338. subMesh.setEffect(null);
  12339. }
  12340. },
  12341. enumerable: true,
  12342. configurable: true
  12343. });
  12344. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12345. get: function () {
  12346. return this._receiveShadows;
  12347. },
  12348. set: function (value) {
  12349. if (this._receiveShadows === value) {
  12350. return;
  12351. }
  12352. this._receiveShadows = value;
  12353. this._markSubMeshesAsLightDirty();
  12354. },
  12355. enumerable: true,
  12356. configurable: true
  12357. });
  12358. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12359. get: function () {
  12360. return this._hasVertexAlpha;
  12361. },
  12362. set: function (value) {
  12363. if (this._hasVertexAlpha === value) {
  12364. return;
  12365. }
  12366. this._hasVertexAlpha = value;
  12367. this._markSubMeshesAsAttributesDirty();
  12368. },
  12369. enumerable: true,
  12370. configurable: true
  12371. });
  12372. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12373. get: function () {
  12374. return this._useVertexColors;
  12375. },
  12376. set: function (value) {
  12377. if (this._useVertexColors === value) {
  12378. return;
  12379. }
  12380. this._useVertexColors = value;
  12381. this._markSubMeshesAsAttributesDirty();
  12382. },
  12383. enumerable: true,
  12384. configurable: true
  12385. });
  12386. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12387. get: function () {
  12388. return this._computeBonesUsingShaders;
  12389. },
  12390. set: function (value) {
  12391. if (this._computeBonesUsingShaders === value) {
  12392. return;
  12393. }
  12394. this._computeBonesUsingShaders = value;
  12395. this._markSubMeshesAsAttributesDirty();
  12396. },
  12397. enumerable: true,
  12398. configurable: true
  12399. });
  12400. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12401. get: function () {
  12402. return this._numBoneInfluencers;
  12403. },
  12404. set: function (value) {
  12405. if (this._numBoneInfluencers === value) {
  12406. return;
  12407. }
  12408. this._numBoneInfluencers = value;
  12409. this._markSubMeshesAsAttributesDirty();
  12410. },
  12411. enumerable: true,
  12412. configurable: true
  12413. });
  12414. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12415. get: function () {
  12416. return this._applyFog;
  12417. },
  12418. set: function (value) {
  12419. if (this._applyFog === value) {
  12420. return;
  12421. }
  12422. this._applyFog = value;
  12423. this._markSubMeshesAsMiscDirty();
  12424. },
  12425. enumerable: true,
  12426. configurable: true
  12427. });
  12428. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12429. get: function () {
  12430. return this._layerMask;
  12431. },
  12432. set: function (value) {
  12433. if (value === this._layerMask) {
  12434. return;
  12435. }
  12436. this._layerMask = value;
  12437. this._resyncLightSources();
  12438. },
  12439. enumerable: true,
  12440. configurable: true
  12441. });
  12442. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12443. get: function () {
  12444. return this._collisionMask;
  12445. },
  12446. set: function (mask) {
  12447. this._collisionMask = !isNaN(mask) ? mask : -1;
  12448. },
  12449. enumerable: true,
  12450. configurable: true
  12451. });
  12452. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12453. get: function () {
  12454. return this._collisionGroup;
  12455. },
  12456. set: function (mask) {
  12457. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12458. },
  12459. enumerable: true,
  12460. configurable: true
  12461. });
  12462. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12463. get: function () {
  12464. return null;
  12465. },
  12466. enumerable: true,
  12467. configurable: true
  12468. });
  12469. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12470. get: function () {
  12471. return this._skeleton;
  12472. },
  12473. set: function (value) {
  12474. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12475. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12476. }
  12477. if (value && value.needInitialSkinMatrix) {
  12478. value._registerMeshWithPoseMatrix(this);
  12479. }
  12480. this._skeleton = value;
  12481. if (!this._skeleton) {
  12482. this._bonesTransformMatrices = null;
  12483. }
  12484. this._markSubMeshesAsAttributesDirty();
  12485. },
  12486. enumerable: true,
  12487. configurable: true
  12488. });
  12489. /**
  12490. * Boolean : true if the mesh has been disposed.
  12491. */
  12492. AbstractMesh.prototype.isDisposed = function () {
  12493. return this._isDisposed;
  12494. };
  12495. /**
  12496. * Returns the string "AbstractMesh"
  12497. */
  12498. AbstractMesh.prototype.getClassName = function () {
  12499. return "AbstractMesh";
  12500. };
  12501. /**
  12502. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12503. */
  12504. AbstractMesh.prototype.toString = function (fullDetails) {
  12505. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12506. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12507. if (this._skeleton) {
  12508. ret += ", skeleton: " + this._skeleton.name;
  12509. }
  12510. if (fullDetails) {
  12511. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12512. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12513. }
  12514. return ret;
  12515. };
  12516. AbstractMesh.prototype._rebuild = function () {
  12517. if (this._occlusionQuery) {
  12518. this._occlusionQuery = null;
  12519. }
  12520. if (this._edgesRenderer) {
  12521. this._edgesRenderer._rebuild();
  12522. }
  12523. if (!this.subMeshes) {
  12524. return;
  12525. }
  12526. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12527. var subMesh = _a[_i];
  12528. subMesh._rebuild();
  12529. }
  12530. };
  12531. AbstractMesh.prototype._resyncLightSources = function () {
  12532. this._lightSources.length = 0;
  12533. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12534. var light = _a[_i];
  12535. if (!light.isEnabled()) {
  12536. continue;
  12537. }
  12538. if (light.canAffectMesh(this)) {
  12539. this._lightSources.push(light);
  12540. }
  12541. }
  12542. this._markSubMeshesAsLightDirty();
  12543. };
  12544. AbstractMesh.prototype._resyncLighSource = function (light) {
  12545. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12546. var index = this._lightSources.indexOf(light);
  12547. if (index === -1) {
  12548. if (!isIn) {
  12549. return;
  12550. }
  12551. this._lightSources.push(light);
  12552. }
  12553. else {
  12554. if (isIn) {
  12555. return;
  12556. }
  12557. this._lightSources.splice(index, 1);
  12558. }
  12559. this._markSubMeshesAsLightDirty();
  12560. };
  12561. AbstractMesh.prototype._removeLightSource = function (light) {
  12562. var index = this._lightSources.indexOf(light);
  12563. if (index === -1) {
  12564. return;
  12565. }
  12566. this._lightSources.splice(index, 1);
  12567. };
  12568. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12569. if (!this.subMeshes) {
  12570. return;
  12571. }
  12572. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12573. var subMesh = _a[_i];
  12574. if (subMesh._materialDefines) {
  12575. func(subMesh._materialDefines);
  12576. }
  12577. }
  12578. };
  12579. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12580. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12581. };
  12582. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12583. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12584. };
  12585. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12586. if (!this.subMeshes) {
  12587. return;
  12588. }
  12589. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12590. var subMesh = _a[_i];
  12591. var material = subMesh.getMaterial();
  12592. if (material) {
  12593. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12594. }
  12595. }
  12596. };
  12597. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12598. /**
  12599. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12600. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12601. * Default : (0.0, 0.0, 0.0)
  12602. */
  12603. get: function () {
  12604. return this._rotation;
  12605. },
  12606. set: function (newRotation) {
  12607. this._rotation = newRotation;
  12608. },
  12609. enumerable: true,
  12610. configurable: true
  12611. });
  12612. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12613. /**
  12614. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12615. * Default : (1.0, 1.0, 1.0)
  12616. */
  12617. get: function () {
  12618. return this._scaling;
  12619. },
  12620. set: function (newScaling) {
  12621. this._scaling = newScaling;
  12622. if (this.physicsImpostor) {
  12623. this.physicsImpostor.forceUpdate();
  12624. }
  12625. },
  12626. enumerable: true,
  12627. configurable: true
  12628. });
  12629. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12630. /**
  12631. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12632. * It's null by default.
  12633. * 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)
  12634. */
  12635. get: function () {
  12636. return this._rotationQuaternion;
  12637. },
  12638. set: function (quaternion) {
  12639. this._rotationQuaternion = quaternion;
  12640. //reset the rotation vector.
  12641. if (quaternion && this.rotation.length()) {
  12642. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12643. }
  12644. },
  12645. enumerable: true,
  12646. configurable: true
  12647. });
  12648. // Methods
  12649. /**
  12650. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12651. * Returns the AbstractMesh.
  12652. */
  12653. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12654. this._poseMatrix.copyFrom(matrix);
  12655. return this;
  12656. };
  12657. /**
  12658. * Returns the mesh Pose matrix.
  12659. * Returned object : Matrix
  12660. */
  12661. AbstractMesh.prototype.getPoseMatrix = function () {
  12662. return this._poseMatrix;
  12663. };
  12664. /**
  12665. * Disables the mesh edger rendering mode.
  12666. * Returns the AbstractMesh.
  12667. */
  12668. AbstractMesh.prototype.disableEdgesRendering = function () {
  12669. if (this._edgesRenderer !== undefined) {
  12670. this._edgesRenderer.dispose();
  12671. this._edgesRenderer = undefined;
  12672. }
  12673. return this;
  12674. };
  12675. /**
  12676. * Enables the edge rendering mode on the mesh.
  12677. * This mode makes the mesh edges visible.
  12678. * Returns the AbstractMesh.
  12679. */
  12680. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12681. if (epsilon === void 0) { epsilon = 0.95; }
  12682. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12683. this.disableEdgesRendering();
  12684. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12685. return this;
  12686. };
  12687. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12688. /**
  12689. * Returns true if the mesh is blocked. Used by the class Mesh.
  12690. * Returns the boolean `false` by default.
  12691. */
  12692. get: function () {
  12693. return false;
  12694. },
  12695. enumerable: true,
  12696. configurable: true
  12697. });
  12698. /**
  12699. * Returns the mesh itself by default, used by the class Mesh.
  12700. * Returned type : AbstractMesh
  12701. */
  12702. AbstractMesh.prototype.getLOD = function (camera) {
  12703. return this;
  12704. };
  12705. /**
  12706. * Returns 0 by default, used by the class Mesh.
  12707. * Returns an integer.
  12708. */
  12709. AbstractMesh.prototype.getTotalVertices = function () {
  12710. return 0;
  12711. };
  12712. /**
  12713. * Returns null by default, used by the class Mesh.
  12714. * Returned type : integer array
  12715. */
  12716. AbstractMesh.prototype.getIndices = function () {
  12717. return null;
  12718. };
  12719. /**
  12720. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12721. * Returned type : float array or Float32Array
  12722. */
  12723. AbstractMesh.prototype.getVerticesData = function (kind) {
  12724. return null;
  12725. };
  12726. /**
  12727. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12728. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12729. * The `data` are either a numeric array either a Float32Array.
  12730. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12731. * 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).
  12732. * Note that a new underlying VertexBuffer object is created each call.
  12733. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12734. *
  12735. * Possible `kind` values :
  12736. * - BABYLON.VertexBuffer.PositionKind
  12737. * - BABYLON.VertexBuffer.UVKind
  12738. * - BABYLON.VertexBuffer.UV2Kind
  12739. * - BABYLON.VertexBuffer.UV3Kind
  12740. * - BABYLON.VertexBuffer.UV4Kind
  12741. * - BABYLON.VertexBuffer.UV5Kind
  12742. * - BABYLON.VertexBuffer.UV6Kind
  12743. * - BABYLON.VertexBuffer.ColorKind
  12744. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12745. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12746. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12747. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12748. *
  12749. * Returns the Mesh.
  12750. */
  12751. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12752. return null;
  12753. };
  12754. /**
  12755. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12756. * If the mesh has no geometry, it is simply returned as it is.
  12757. * The `data` are either a numeric array either a Float32Array.
  12758. * No new underlying VertexBuffer object is created.
  12759. * 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.
  12760. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12761. *
  12762. * Possible `kind` values :
  12763. * - BABYLON.VertexBuffer.PositionKind
  12764. * - BABYLON.VertexBuffer.UVKind
  12765. * - BABYLON.VertexBuffer.UV2Kind
  12766. * - BABYLON.VertexBuffer.UV3Kind
  12767. * - BABYLON.VertexBuffer.UV4Kind
  12768. * - BABYLON.VertexBuffer.UV5Kind
  12769. * - BABYLON.VertexBuffer.UV6Kind
  12770. * - BABYLON.VertexBuffer.ColorKind
  12771. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12772. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12773. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12774. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12775. *
  12776. * Returns the Mesh.
  12777. */
  12778. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12779. return null;
  12780. };
  12781. /**
  12782. * Sets the mesh indices.
  12783. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12784. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12785. * This method creates a new index buffer each call.
  12786. * Returns the Mesh.
  12787. */
  12788. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12789. return null;
  12790. };
  12791. /** Returns false by default, used by the class Mesh.
  12792. * Returns a boolean
  12793. */
  12794. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12795. return false;
  12796. };
  12797. /**
  12798. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12799. * Returns a BoundingInfo
  12800. */
  12801. AbstractMesh.prototype.getBoundingInfo = function () {
  12802. if (this._masterMesh) {
  12803. return this._masterMesh.getBoundingInfo();
  12804. }
  12805. if (!this._boundingInfo) {
  12806. this._updateBoundingInfo();
  12807. }
  12808. return this._boundingInfo;
  12809. };
  12810. /**
  12811. * Sets a mesh new object BoundingInfo.
  12812. * Returns the AbstractMesh.
  12813. */
  12814. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12815. this._boundingInfo = boundingInfo;
  12816. return this;
  12817. };
  12818. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12819. get: function () {
  12820. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12821. },
  12822. enumerable: true,
  12823. configurable: true
  12824. });
  12825. AbstractMesh.prototype._preActivate = function () {
  12826. };
  12827. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12828. };
  12829. AbstractMesh.prototype._activate = function (renderId) {
  12830. this._renderId = renderId;
  12831. };
  12832. /**
  12833. * Returns the last update of the World matrix
  12834. * Returns a Matrix.
  12835. */
  12836. AbstractMesh.prototype.getWorldMatrix = function () {
  12837. if (this._masterMesh) {
  12838. return this._masterMesh.getWorldMatrix();
  12839. }
  12840. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12841. this.computeWorldMatrix();
  12842. }
  12843. return this._worldMatrix;
  12844. };
  12845. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12846. /**
  12847. * Returns directly the last state of the mesh World matrix.
  12848. * A Matrix is returned.
  12849. */
  12850. get: function () {
  12851. return this._worldMatrix;
  12852. },
  12853. enumerable: true,
  12854. configurable: true
  12855. });
  12856. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12857. /**
  12858. * Returns the current mesh absolute position.
  12859. * Retuns a Vector3.
  12860. */
  12861. get: function () {
  12862. return this._absolutePosition;
  12863. },
  12864. enumerable: true,
  12865. configurable: true
  12866. });
  12867. /**
  12868. * Prevents the World matrix to be computed any longer.
  12869. * Returns the AbstractMesh.
  12870. */
  12871. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12872. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12873. this.computeWorldMatrix(true);
  12874. this._isWorldMatrixFrozen = true;
  12875. return this;
  12876. };
  12877. /**
  12878. * Allows back the World matrix computation.
  12879. * Returns the AbstractMesh.
  12880. */
  12881. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12882. this._isWorldMatrixFrozen = false;
  12883. this.computeWorldMatrix(true);
  12884. return this;
  12885. };
  12886. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12887. /**
  12888. * True if the World matrix has been frozen.
  12889. * Returns a boolean.
  12890. */
  12891. get: function () {
  12892. return this._isWorldMatrixFrozen;
  12893. },
  12894. enumerable: true,
  12895. configurable: true
  12896. });
  12897. /**
  12898. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12899. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12900. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12901. * The passed axis is also normalized.
  12902. * Returns the AbstractMesh.
  12903. */
  12904. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12905. axis.normalize();
  12906. if (!this.rotationQuaternion) {
  12907. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12908. this.rotation = BABYLON.Vector3.Zero();
  12909. }
  12910. var rotationQuaternion;
  12911. if (!space || space === BABYLON.Space.LOCAL) {
  12912. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12913. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12914. }
  12915. else {
  12916. if (this.parent) {
  12917. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12918. invertParentWorldMatrix.invert();
  12919. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12920. }
  12921. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12922. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12923. }
  12924. return this;
  12925. };
  12926. /**
  12927. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12928. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12929. * The passed axis is also normalized.
  12930. * Returns the AbstractMesh.
  12931. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12932. */
  12933. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12934. axis.normalize();
  12935. if (!this.rotationQuaternion) {
  12936. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12937. this.rotation.copyFromFloats(0, 0, 0);
  12938. }
  12939. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12940. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12941. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12942. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12943. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12944. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12945. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12946. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12947. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12948. return this;
  12949. };
  12950. /**
  12951. * Translates the mesh along the axis vector for the passed distance in the given space.
  12952. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12953. * Returns the AbstractMesh.
  12954. */
  12955. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12956. var displacementVector = axis.scale(distance);
  12957. if (!space || space === BABYLON.Space.LOCAL) {
  12958. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12959. this.setPositionWithLocalVector(tempV3);
  12960. }
  12961. else {
  12962. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12963. }
  12964. return this;
  12965. };
  12966. /**
  12967. * Adds a rotation step to the mesh current rotation.
  12968. * x, y, z are Euler angles expressed in radians.
  12969. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12970. * This means this rotation is made in the mesh local space only.
  12971. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12972. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12973. * ```javascript
  12974. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12975. * ```
  12976. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12977. * 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.
  12978. * Returns the AbstractMesh.
  12979. */
  12980. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12981. var rotationQuaternion;
  12982. if (this.rotationQuaternion) {
  12983. rotationQuaternion = this.rotationQuaternion;
  12984. }
  12985. else {
  12986. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12987. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12988. }
  12989. var accumulation = BABYLON.Tmp.Quaternion[0];
  12990. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12991. rotationQuaternion.multiplyInPlace(accumulation);
  12992. if (!this.rotationQuaternion) {
  12993. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12994. }
  12995. return this;
  12996. };
  12997. /**
  12998. * Retuns the mesh absolute position in the World.
  12999. * Returns a Vector3.
  13000. */
  13001. AbstractMesh.prototype.getAbsolutePosition = function () {
  13002. this.computeWorldMatrix();
  13003. return this._absolutePosition;
  13004. };
  13005. /**
  13006. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13007. * Returns the AbstractMesh.
  13008. */
  13009. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13010. if (!absolutePosition) {
  13011. return;
  13012. }
  13013. var absolutePositionX;
  13014. var absolutePositionY;
  13015. var absolutePositionZ;
  13016. if (absolutePosition.x === undefined) {
  13017. if (arguments.length < 3) {
  13018. return;
  13019. }
  13020. absolutePositionX = arguments[0];
  13021. absolutePositionY = arguments[1];
  13022. absolutePositionZ = arguments[2];
  13023. }
  13024. else {
  13025. absolutePositionX = absolutePosition.x;
  13026. absolutePositionY = absolutePosition.y;
  13027. absolutePositionZ = absolutePosition.z;
  13028. }
  13029. if (this.parent) {
  13030. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13031. invertParentWorldMatrix.invert();
  13032. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13033. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13034. }
  13035. else {
  13036. this.position.x = absolutePositionX;
  13037. this.position.y = absolutePositionY;
  13038. this.position.z = absolutePositionZ;
  13039. }
  13040. return this;
  13041. };
  13042. // ================================== Point of View Movement =================================
  13043. /**
  13044. * Perform relative position change from the point of view of behind the front of the mesh.
  13045. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13046. * Supports definition of mesh facing forward or backward.
  13047. * @param {number} amountRight
  13048. * @param {number} amountUp
  13049. * @param {number} amountForward
  13050. *
  13051. * Returns the AbstractMesh.
  13052. */
  13053. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13054. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13055. return this;
  13056. };
  13057. /**
  13058. * Calculate relative position change from the point of view of behind the front of the mesh.
  13059. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13060. * Supports definition of mesh facing forward or backward.
  13061. * @param {number} amountRight
  13062. * @param {number} amountUp
  13063. * @param {number} amountForward
  13064. *
  13065. * Returns a new Vector3.
  13066. */
  13067. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13068. var rotMatrix = new BABYLON.Matrix();
  13069. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13070. rotQuaternion.toRotationMatrix(rotMatrix);
  13071. var translationDelta = BABYLON.Vector3.Zero();
  13072. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13073. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13074. return translationDelta;
  13075. };
  13076. // ================================== Point of View Rotation =================================
  13077. /**
  13078. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13079. * Supports definition of mesh facing forward or backward.
  13080. * @param {number} flipBack
  13081. * @param {number} twirlClockwise
  13082. * @param {number} tiltRight
  13083. *
  13084. * Returns the AbstractMesh.
  13085. */
  13086. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13087. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13088. return this;
  13089. };
  13090. /**
  13091. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13092. * Supports definition of mesh facing forward or backward.
  13093. * @param {number} flipBack
  13094. * @param {number} twirlClockwise
  13095. * @param {number} tiltRight
  13096. *
  13097. * Returns a new Vector3.
  13098. */
  13099. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13100. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13101. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13102. };
  13103. /**
  13104. * Sets a new pivot matrix to the mesh.
  13105. * Returns the AbstractMesh.
  13106. */
  13107. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  13108. this._pivotMatrix = matrix;
  13109. this._cache.pivotMatrixUpdated = true;
  13110. return this;
  13111. };
  13112. /**
  13113. * Returns the mesh pivot matrix.
  13114. * Default : Identity.
  13115. * A Matrix is returned.
  13116. */
  13117. AbstractMesh.prototype.getPivotMatrix = function () {
  13118. return this._pivotMatrix;
  13119. };
  13120. AbstractMesh.prototype._isSynchronized = function () {
  13121. if (this._isDirty) {
  13122. return false;
  13123. }
  13124. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13125. return false;
  13126. if (this._cache.pivotMatrixUpdated) {
  13127. return false;
  13128. }
  13129. if (this.infiniteDistance) {
  13130. return false;
  13131. }
  13132. if (!this._cache.position.equals(this.position))
  13133. return false;
  13134. if (this.rotationQuaternion) {
  13135. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13136. return false;
  13137. }
  13138. if (!this._cache.rotation.equals(this.rotation))
  13139. return false;
  13140. if (!this._cache.scaling.equals(this.scaling))
  13141. return false;
  13142. return true;
  13143. };
  13144. AbstractMesh.prototype._initCache = function () {
  13145. _super.prototype._initCache.call(this);
  13146. this._cache.localMatrixUpdated = false;
  13147. this._cache.position = BABYLON.Vector3.Zero();
  13148. this._cache.scaling = BABYLON.Vector3.Zero();
  13149. this._cache.rotation = BABYLON.Vector3.Zero();
  13150. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13151. this._cache.billboardMode = -1;
  13152. };
  13153. AbstractMesh.prototype.markAsDirty = function (property) {
  13154. if (property === "rotation") {
  13155. this.rotationQuaternion = null;
  13156. }
  13157. this._currentRenderId = Number.MAX_VALUE;
  13158. this._isDirty = true;
  13159. return this;
  13160. };
  13161. /**
  13162. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13163. * Returns the AbstractMesh.
  13164. */
  13165. AbstractMesh.prototype._updateBoundingInfo = function () {
  13166. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13167. this._boundingInfo.update(this.worldMatrixFromCache);
  13168. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13169. return this;
  13170. };
  13171. /**
  13172. * Update a mesh's children BoundingInfo objects only.
  13173. * Returns the AbstractMesh.
  13174. */
  13175. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13176. if (!this.subMeshes) {
  13177. return;
  13178. }
  13179. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13180. var subMesh = this.subMeshes[subIndex];
  13181. if (!subMesh.IsGlobal) {
  13182. subMesh.updateBoundingInfo(matrix);
  13183. }
  13184. }
  13185. return this;
  13186. };
  13187. /**
  13188. * Computes the mesh World matrix and returns it.
  13189. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13190. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13191. * If the parameter `force`is set to `true`, the actual computation is done.
  13192. * Returns the mesh World Matrix.
  13193. */
  13194. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13195. if (this._isWorldMatrixFrozen) {
  13196. return this._worldMatrix;
  13197. }
  13198. if (!force && this.isSynchronized(true)) {
  13199. this._currentRenderId = this.getScene().getRenderId();
  13200. return this._worldMatrix;
  13201. }
  13202. this._cache.position.copyFrom(this.position);
  13203. this._cache.scaling.copyFrom(this.scaling);
  13204. this._cache.pivotMatrixUpdated = false;
  13205. this._cache.billboardMode = this.billboardMode;
  13206. this._currentRenderId = this.getScene().getRenderId();
  13207. this._isDirty = false;
  13208. // Scaling
  13209. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13210. // Rotation
  13211. //rotate, if quaternion is set and rotation was used
  13212. if (this.rotationQuaternion) {
  13213. var len = this.rotation.length();
  13214. if (len) {
  13215. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13216. this.rotation.copyFromFloats(0, 0, 0);
  13217. }
  13218. }
  13219. if (this.rotationQuaternion) {
  13220. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13221. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13222. }
  13223. else {
  13224. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13225. this._cache.rotation.copyFrom(this.rotation);
  13226. }
  13227. // Translation
  13228. if (this.infiniteDistance && !this.parent) {
  13229. var camera = this.getScene().activeCamera;
  13230. if (camera) {
  13231. var cameraWorldMatrix = camera.getWorldMatrix();
  13232. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13233. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13234. }
  13235. }
  13236. else {
  13237. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13238. }
  13239. // Composing transformations
  13240. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13241. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13242. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13243. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13244. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13245. // Need to decompose each rotation here
  13246. var currentPosition = BABYLON.Tmp.Vector3[3];
  13247. if (this.parent && this.parent.getWorldMatrix) {
  13248. if (this._meshToBoneReferal) {
  13249. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13250. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13251. }
  13252. else {
  13253. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13254. }
  13255. }
  13256. else {
  13257. currentPosition.copyFrom(this.position);
  13258. }
  13259. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13260. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13261. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13262. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13263. }
  13264. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13265. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13266. }
  13267. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13268. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13269. }
  13270. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13271. }
  13272. else {
  13273. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13274. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13275. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13276. }
  13277. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13278. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13279. }
  13280. // Local world
  13281. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13282. // Parent
  13283. if (this.parent && this.parent.getWorldMatrix) {
  13284. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13285. if (this._meshToBoneReferal) {
  13286. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13287. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13288. }
  13289. else {
  13290. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13291. }
  13292. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13293. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13294. this._worldMatrix.copyFrom(this._localWorld);
  13295. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13296. }
  13297. else {
  13298. if (this._meshToBoneReferal) {
  13299. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13300. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13301. }
  13302. else {
  13303. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13304. }
  13305. }
  13306. this._markSyncedWithParent();
  13307. }
  13308. else {
  13309. this._worldMatrix.copyFrom(this._localWorld);
  13310. }
  13311. // Bounding info
  13312. this._updateBoundingInfo();
  13313. // Absolute position
  13314. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13315. // Callbacks
  13316. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13317. if (!this._poseMatrix) {
  13318. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13319. }
  13320. return this._worldMatrix;
  13321. };
  13322. /**
  13323. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13324. * @param func: callback function to add
  13325. *
  13326. * Returns the AbstractMesh.
  13327. */
  13328. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13329. this.onAfterWorldMatrixUpdateObservable.add(func);
  13330. return this;
  13331. };
  13332. /**
  13333. * Removes a registered callback function.
  13334. * Returns the AbstractMesh.
  13335. */
  13336. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13337. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13338. return this;
  13339. };
  13340. /**
  13341. * Sets the mesh position in its local space.
  13342. * Returns the AbstractMesh.
  13343. */
  13344. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13345. this.computeWorldMatrix();
  13346. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13347. return this;
  13348. };
  13349. /**
  13350. * Returns the mesh position in the local space from the current World matrix values.
  13351. * Returns a new Vector3.
  13352. */
  13353. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13354. this.computeWorldMatrix();
  13355. var invLocalWorldMatrix = this._localWorld.clone();
  13356. invLocalWorldMatrix.invert();
  13357. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13358. };
  13359. /**
  13360. * Translates the mesh along the passed Vector3 in its local space.
  13361. * Returns the AbstractMesh.
  13362. */
  13363. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13364. this.computeWorldMatrix(true);
  13365. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13366. return this;
  13367. };
  13368. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13369. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13370. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13371. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13372. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13373. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13374. /// <returns>Mesh oriented towards targetMesh</returns>
  13375. if (yawCor === void 0) { yawCor = 0; }
  13376. if (pitchCor === void 0) { pitchCor = 0; }
  13377. if (rollCor === void 0) { rollCor = 0; }
  13378. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13379. var dv = AbstractMesh._lookAtVectorCache;
  13380. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13381. targetPoint.subtractToRef(pos, dv);
  13382. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13383. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13384. var pitch = Math.atan2(dv.y, len);
  13385. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13386. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13387. return this;
  13388. };
  13389. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13390. this._meshToBoneReferal = affectedMesh;
  13391. this.parent = bone;
  13392. if (bone.getWorldMatrix().determinant() < 0) {
  13393. this.scalingDeterminant *= -1;
  13394. }
  13395. return this;
  13396. };
  13397. AbstractMesh.prototype.detachFromBone = function () {
  13398. if (this.parent.getWorldMatrix().determinant() < 0) {
  13399. this.scalingDeterminant *= -1;
  13400. }
  13401. this._meshToBoneReferal = null;
  13402. this.parent = null;
  13403. return this;
  13404. };
  13405. /**
  13406. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13407. * A mesh is in the frustum if its bounding box intersects the frustum.
  13408. * Boolean returned.
  13409. */
  13410. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13411. return this._boundingInfo.isInFrustum(frustumPlanes);
  13412. };
  13413. /**
  13414. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13415. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13416. * Boolean returned.
  13417. */
  13418. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13419. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13420. ;
  13421. };
  13422. /**
  13423. * True if the mesh intersects another mesh or a SolidParticle object.
  13424. * 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)
  13425. * Returns a boolean.
  13426. */
  13427. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13428. if (!this._boundingInfo || !mesh._boundingInfo) {
  13429. return false;
  13430. }
  13431. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13432. };
  13433. /**
  13434. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13435. * Returns a boolean.
  13436. */
  13437. AbstractMesh.prototype.intersectsPoint = function (point) {
  13438. if (!this._boundingInfo) {
  13439. return false;
  13440. }
  13441. return this._boundingInfo.intersectsPoint(point);
  13442. };
  13443. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13444. return this.physicsImpostor;
  13445. };
  13446. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13447. if (!camera) {
  13448. camera = this.getScene().activeCamera;
  13449. }
  13450. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13451. };
  13452. /**
  13453. * Returns the distance from the mesh to the active camera.
  13454. * Returns a float.
  13455. */
  13456. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13457. if (!camera) {
  13458. camera = this.getScene().activeCamera;
  13459. }
  13460. return this.absolutePosition.subtract(camera.position).length();
  13461. };
  13462. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13463. if (!this.physicsImpostor) {
  13464. return;
  13465. }
  13466. this.physicsImpostor.applyImpulse(force, contactPoint);
  13467. return this;
  13468. };
  13469. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13470. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13471. return;
  13472. }
  13473. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13474. mainPivot: pivot1,
  13475. connectedPivot: pivot2,
  13476. nativeParams: options
  13477. });
  13478. return this;
  13479. };
  13480. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13481. // Collisions
  13482. /**
  13483. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13484. * Default `false`.
  13485. */
  13486. get: function () {
  13487. return this._checkCollisions;
  13488. },
  13489. set: function (collisionEnabled) {
  13490. this._checkCollisions = collisionEnabled;
  13491. if (this.getScene().workerCollisions) {
  13492. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13493. }
  13494. },
  13495. enumerable: true,
  13496. configurable: true
  13497. });
  13498. AbstractMesh.prototype.moveWithCollisions = function (direction) {
  13499. var globalPosition = this.getAbsolutePosition();
  13500. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13501. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13502. if (!this._collider) {
  13503. this._collider = new BABYLON.Collider();
  13504. }
  13505. this._collider.radius = this.ellipsoid;
  13506. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, direction, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13507. return this;
  13508. };
  13509. // Submeshes octree
  13510. /**
  13511. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13512. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13513. * Returns an Octree of submeshes.
  13514. */
  13515. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13516. if (maxCapacity === void 0) { maxCapacity = 64; }
  13517. if (maxDepth === void 0) { maxDepth = 2; }
  13518. if (!this._submeshesOctree) {
  13519. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13520. }
  13521. this.computeWorldMatrix(true);
  13522. // Update octree
  13523. var bbox = this.getBoundingInfo().boundingBox;
  13524. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13525. return this._submeshesOctree;
  13526. };
  13527. // Collisions
  13528. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13529. this._generatePointsArray();
  13530. // Transformation
  13531. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13532. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13533. subMesh._lastColliderWorldVertices = [];
  13534. subMesh._trianglePlanes = [];
  13535. var start = subMesh.verticesStart;
  13536. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13537. for (var i = start; i < end; i++) {
  13538. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13539. }
  13540. }
  13541. // Collide
  13542. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13543. if (collider.collisionFound) {
  13544. collider.collidedMesh = this;
  13545. }
  13546. return this;
  13547. };
  13548. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13549. var subMeshes;
  13550. var len;
  13551. // Octrees
  13552. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13553. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13554. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13555. len = intersections.length;
  13556. subMeshes = intersections.data;
  13557. }
  13558. else {
  13559. subMeshes = this.subMeshes;
  13560. len = subMeshes.length;
  13561. }
  13562. for (var index = 0; index < len; index++) {
  13563. var subMesh = subMeshes[index];
  13564. // Bounding test
  13565. if (len > 1 && !subMesh._checkCollision(collider))
  13566. continue;
  13567. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13568. }
  13569. return this;
  13570. };
  13571. AbstractMesh.prototype._checkCollision = function (collider) {
  13572. // Bounding box test
  13573. if (!this._boundingInfo._checkCollision(collider))
  13574. return this;
  13575. // Transformation matrix
  13576. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13577. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13578. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13579. return this;
  13580. };
  13581. // Picking
  13582. AbstractMesh.prototype._generatePointsArray = function () {
  13583. return false;
  13584. };
  13585. /**
  13586. * Checks if the passed Ray intersects with the mesh.
  13587. * Returns an object PickingInfo.
  13588. */
  13589. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13590. var pickingInfo = new BABYLON.PickingInfo();
  13591. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13592. return pickingInfo;
  13593. }
  13594. if (!this._generatePointsArray()) {
  13595. return pickingInfo;
  13596. }
  13597. var intersectInfo = null;
  13598. // Octrees
  13599. var subMeshes;
  13600. var len;
  13601. if (this._submeshesOctree && this.useOctreeForPicking) {
  13602. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13603. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13604. len = intersections.length;
  13605. subMeshes = intersections.data;
  13606. }
  13607. else {
  13608. subMeshes = this.subMeshes;
  13609. len = subMeshes.length;
  13610. }
  13611. for (var index = 0; index < len; index++) {
  13612. var subMesh = subMeshes[index];
  13613. // Bounding test
  13614. if (len > 1 && !subMesh.canIntersects(ray))
  13615. continue;
  13616. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13617. if (currentIntersectInfo) {
  13618. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13619. intersectInfo = currentIntersectInfo;
  13620. intersectInfo.subMeshId = index;
  13621. if (fastCheck) {
  13622. break;
  13623. }
  13624. }
  13625. }
  13626. }
  13627. if (intersectInfo) {
  13628. // Get picked point
  13629. var world = this.getWorldMatrix();
  13630. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13631. var direction = ray.direction.clone();
  13632. direction = direction.scale(intersectInfo.distance);
  13633. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13634. var pickedPoint = worldOrigin.add(worldDirection);
  13635. // Return result
  13636. pickingInfo.hit = true;
  13637. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13638. pickingInfo.pickedPoint = pickedPoint;
  13639. pickingInfo.pickedMesh = this;
  13640. pickingInfo.bu = intersectInfo.bu;
  13641. pickingInfo.bv = intersectInfo.bv;
  13642. pickingInfo.faceId = intersectInfo.faceId;
  13643. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13644. return pickingInfo;
  13645. }
  13646. return pickingInfo;
  13647. };
  13648. /**
  13649. * Clones the mesh, used by the class Mesh.
  13650. * Just returns `null` for an AbstractMesh.
  13651. */
  13652. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13653. return null;
  13654. };
  13655. /**
  13656. * Disposes all the mesh submeshes.
  13657. * Returns the AbstractMesh.
  13658. */
  13659. AbstractMesh.prototype.releaseSubMeshes = function () {
  13660. if (this.subMeshes) {
  13661. while (this.subMeshes.length) {
  13662. this.subMeshes[0].dispose();
  13663. }
  13664. }
  13665. else {
  13666. this.subMeshes = new Array();
  13667. }
  13668. return this;
  13669. };
  13670. /**
  13671. * Disposes the AbstractMesh.
  13672. * Some internal references are kept for further use.
  13673. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13674. * Returns nothing.
  13675. */
  13676. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13677. var _this = this;
  13678. var index;
  13679. // Action manager
  13680. if (this.actionManager) {
  13681. this.actionManager.dispose();
  13682. this.actionManager = null;
  13683. }
  13684. // Skeleton
  13685. this.skeleton = null;
  13686. // Animations
  13687. this.getScene().stopAnimation(this);
  13688. // Physics
  13689. if (this.physicsImpostor) {
  13690. this.physicsImpostor.dispose();
  13691. }
  13692. // Intersections in progress
  13693. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13694. var other = this._intersectionsInProgress[index];
  13695. var pos = other._intersectionsInProgress.indexOf(this);
  13696. other._intersectionsInProgress.splice(pos, 1);
  13697. }
  13698. this._intersectionsInProgress = [];
  13699. // Lights
  13700. var lights = this.getScene().lights;
  13701. lights.forEach(function (light) {
  13702. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13703. if (meshIndex !== -1) {
  13704. light.includedOnlyMeshes.splice(meshIndex, 1);
  13705. }
  13706. meshIndex = light.excludedMeshes.indexOf(_this);
  13707. if (meshIndex !== -1) {
  13708. light.excludedMeshes.splice(meshIndex, 1);
  13709. }
  13710. // Shadow generators
  13711. var generator = light.getShadowGenerator();
  13712. if (generator) {
  13713. var shadowMap = generator.getShadowMap();
  13714. meshIndex = shadowMap.renderList.indexOf(_this);
  13715. if (meshIndex !== -1) {
  13716. shadowMap.renderList.splice(meshIndex, 1);
  13717. }
  13718. }
  13719. });
  13720. // Edges
  13721. if (this._edgesRenderer) {
  13722. this._edgesRenderer.dispose();
  13723. this._edgesRenderer = null;
  13724. }
  13725. // SubMeshes
  13726. if (this.getClassName() !== "InstancedMesh") {
  13727. this.releaseSubMeshes();
  13728. }
  13729. // Octree
  13730. var sceneOctree = this.getScene().selectionOctree;
  13731. if (sceneOctree) {
  13732. var index = sceneOctree.dynamicContent.indexOf(this);
  13733. if (index !== -1) {
  13734. sceneOctree.dynamicContent.splice(index, 1);
  13735. }
  13736. }
  13737. // Query
  13738. var engine = this.getScene().getEngine();
  13739. if (this._occlusionQuery) {
  13740. this._isOcclusionQueryInProgress = false;
  13741. engine.deleteQuery(this._occlusionQuery);
  13742. this._occlusionQuery = null;
  13743. }
  13744. // Engine
  13745. engine.wipeCaches();
  13746. // Remove from scene
  13747. this.getScene().removeMesh(this);
  13748. if (!doNotRecurse) {
  13749. // Particles
  13750. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13751. if (this.getScene().particleSystems[index].emitter === this) {
  13752. this.getScene().particleSystems[index].dispose();
  13753. index--;
  13754. }
  13755. }
  13756. // Children
  13757. var objects = this.getDescendants(true);
  13758. for (index = 0; index < objects.length; index++) {
  13759. objects[index].dispose();
  13760. }
  13761. }
  13762. else {
  13763. var childMeshes = this.getChildMeshes(true);
  13764. for (index = 0; index < childMeshes.length; index++) {
  13765. var child = childMeshes[index];
  13766. child.parent = null;
  13767. child.computeWorldMatrix(true);
  13768. }
  13769. }
  13770. // facet data
  13771. if (this._facetDataEnabled) {
  13772. this.disableFacetData();
  13773. }
  13774. this.onAfterWorldMatrixUpdateObservable.clear();
  13775. this.onCollideObservable.clear();
  13776. this.onCollisionPositionChangeObservable.clear();
  13777. this._isDisposed = true;
  13778. _super.prototype.dispose.call(this);
  13779. };
  13780. /**
  13781. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13782. * This Vector3 is expressed in the World space.
  13783. */
  13784. AbstractMesh.prototype.getDirection = function (localAxis) {
  13785. var result = BABYLON.Vector3.Zero();
  13786. this.getDirectionToRef(localAxis, result);
  13787. return result;
  13788. };
  13789. /**
  13790. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13791. * localAxis is expressed in the mesh local space.
  13792. * result is computed in the Wordl space from the mesh World matrix.
  13793. * Returns the AbstractMesh.
  13794. */
  13795. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13796. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13797. return this;
  13798. };
  13799. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13800. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13801. if (this.getScene().getRenderId() == 0) {
  13802. this.computeWorldMatrix(true);
  13803. }
  13804. var wm = this.getWorldMatrix();
  13805. if (space == BABYLON.Space.WORLD) {
  13806. var tmat = BABYLON.Tmp.Matrix[0];
  13807. wm.invertToRef(tmat);
  13808. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13809. }
  13810. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13811. this._pivotMatrix.m[12] = -point.x;
  13812. this._pivotMatrix.m[13] = -point.y;
  13813. this._pivotMatrix.m[14] = -point.z;
  13814. this._cache.pivotMatrixUpdated = true;
  13815. return this;
  13816. };
  13817. /**
  13818. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13819. */
  13820. AbstractMesh.prototype.getPivotPoint = function () {
  13821. var point = BABYLON.Vector3.Zero();
  13822. this.getPivotPointToRef(point);
  13823. return point;
  13824. };
  13825. /**
  13826. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13827. * Returns the AbstractMesh.
  13828. */
  13829. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13830. result.x = -this._pivotMatrix.m[12];
  13831. result.y = -this._pivotMatrix.m[13];
  13832. result.z = -this._pivotMatrix.m[14];
  13833. return this;
  13834. };
  13835. /**
  13836. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13837. */
  13838. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13839. var point = BABYLON.Vector3.Zero();
  13840. this.getAbsolutePivotPointToRef(point);
  13841. return point;
  13842. };
  13843. /**
  13844. * Defines the passed mesh as the parent of the current mesh.
  13845. * Returns the AbstractMesh.
  13846. */
  13847. AbstractMesh.prototype.setParent = function (mesh) {
  13848. var child = this;
  13849. var parent = mesh;
  13850. if (mesh == null) {
  13851. var rotation = BABYLON.Tmp.Quaternion[0];
  13852. var position = BABYLON.Tmp.Vector3[0];
  13853. var scale = BABYLON.Tmp.Vector3[1];
  13854. child.getWorldMatrix().decompose(scale, rotation, position);
  13855. if (child.rotationQuaternion) {
  13856. child.rotationQuaternion.copyFrom(rotation);
  13857. }
  13858. else {
  13859. rotation.toEulerAnglesToRef(child.rotation);
  13860. }
  13861. child.position.x = position.x;
  13862. child.position.y = position.y;
  13863. child.position.z = position.z;
  13864. }
  13865. else {
  13866. var rotation = BABYLON.Tmp.Quaternion[0];
  13867. var position = BABYLON.Tmp.Vector3[0];
  13868. var scale = BABYLON.Tmp.Vector3[1];
  13869. var m1 = BABYLON.Tmp.Matrix[0];
  13870. var m2 = BABYLON.Tmp.Matrix[1];
  13871. parent.getWorldMatrix().decompose(scale, rotation, position);
  13872. rotation.toRotationMatrix(m1);
  13873. m2.setTranslation(position);
  13874. m2.multiplyToRef(m1, m1);
  13875. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13876. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13877. m.decompose(scale, rotation, position);
  13878. if (child.rotationQuaternion) {
  13879. child.rotationQuaternion.copyFrom(rotation);
  13880. }
  13881. else {
  13882. rotation.toEulerAnglesToRef(child.rotation);
  13883. }
  13884. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13885. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13886. m.decompose(scale, rotation, position);
  13887. child.position.x = position.x;
  13888. child.position.y = position.y;
  13889. child.position.z = position.z;
  13890. }
  13891. child.parent = parent;
  13892. return this;
  13893. };
  13894. /**
  13895. * Adds the passed mesh as a child to the current mesh.
  13896. * Returns the AbstractMesh.
  13897. */
  13898. AbstractMesh.prototype.addChild = function (mesh) {
  13899. mesh.setParent(this);
  13900. return this;
  13901. };
  13902. /**
  13903. * Removes the passed mesh from the current mesh children list.
  13904. * Returns the AbstractMesh.
  13905. */
  13906. AbstractMesh.prototype.removeChild = function (mesh) {
  13907. mesh.setParent(null);
  13908. return this;
  13909. };
  13910. /**
  13911. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13912. * Returns the AbstractMesh.
  13913. */
  13914. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13915. result.x = this._pivotMatrix.m[12];
  13916. result.y = this._pivotMatrix.m[13];
  13917. result.z = this._pivotMatrix.m[14];
  13918. this.getPivotPointToRef(result);
  13919. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13920. return this;
  13921. };
  13922. // Facet data
  13923. /**
  13924. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13925. * Returns the AbstractMesh.
  13926. */
  13927. AbstractMesh.prototype._initFacetData = function () {
  13928. if (!this._facetNormals) {
  13929. this._facetNormals = new Array();
  13930. }
  13931. if (!this._facetPositions) {
  13932. this._facetPositions = new Array();
  13933. }
  13934. if (!this._facetPartitioning) {
  13935. this._facetPartitioning = new Array();
  13936. }
  13937. this._facetNb = this.getIndices().length / 3;
  13938. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13939. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13940. for (var f = 0; f < this._facetNb; f++) {
  13941. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13942. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13943. }
  13944. this._facetDataEnabled = true;
  13945. return this;
  13946. };
  13947. /**
  13948. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13949. * This method can be called within the render loop.
  13950. * 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.
  13951. * Returns the AbstractMesh.
  13952. */
  13953. AbstractMesh.prototype.updateFacetData = function () {
  13954. if (!this._facetDataEnabled) {
  13955. this._initFacetData();
  13956. }
  13957. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13958. var indices = this.getIndices();
  13959. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13960. var bInfo = this.getBoundingInfo();
  13961. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13962. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13963. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13964. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13965. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13966. this._subDiv.max = this._partitioningSubdivisions;
  13967. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13968. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13969. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13970. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13971. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13972. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13973. // set the parameters for ComputeNormals()
  13974. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13975. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13976. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13977. this._facetParameters.bInfo = bInfo;
  13978. this._facetParameters.bbSize = this._bbSize;
  13979. this._facetParameters.subDiv = this._subDiv;
  13980. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13981. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13982. return this;
  13983. };
  13984. /**
  13985. * Returns the facetLocalNormals array.
  13986. * The normals are expressed in the mesh local space.
  13987. */
  13988. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13989. if (!this._facetNormals) {
  13990. this.updateFacetData();
  13991. }
  13992. return this._facetNormals;
  13993. };
  13994. /**
  13995. * Returns the facetLocalPositions array.
  13996. * The facet positions are expressed in the mesh local space.
  13997. */
  13998. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13999. if (!this._facetPositions) {
  14000. this.updateFacetData();
  14001. }
  14002. return this._facetPositions;
  14003. };
  14004. /**
  14005. * Returns the facetLocalPartioning array.
  14006. */
  14007. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14008. if (!this._facetPartitioning) {
  14009. this.updateFacetData();
  14010. }
  14011. return this._facetPartitioning;
  14012. };
  14013. /**
  14014. * Returns the i-th facet position in the world system.
  14015. * This method allocates a new Vector3 per call.
  14016. */
  14017. AbstractMesh.prototype.getFacetPosition = function (i) {
  14018. var pos = BABYLON.Vector3.Zero();
  14019. this.getFacetPositionToRef(i, pos);
  14020. return pos;
  14021. };
  14022. /**
  14023. * Sets the reference Vector3 with the i-th facet position in the world system.
  14024. * Returns the AbstractMesh.
  14025. */
  14026. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14027. var localPos = (this.getFacetLocalPositions())[i];
  14028. var world = this.getWorldMatrix();
  14029. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14030. return this;
  14031. };
  14032. /**
  14033. * Returns the i-th facet normal in the world system.
  14034. * This method allocates a new Vector3 per call.
  14035. */
  14036. AbstractMesh.prototype.getFacetNormal = function (i) {
  14037. var norm = BABYLON.Vector3.Zero();
  14038. this.getFacetNormalToRef(i, norm);
  14039. return norm;
  14040. };
  14041. /**
  14042. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14043. * Returns the AbstractMesh.
  14044. */
  14045. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14046. var localNorm = (this.getFacetLocalNormals())[i];
  14047. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14048. return this;
  14049. };
  14050. /**
  14051. * 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).
  14052. */
  14053. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14054. var bInfo = this.getBoundingInfo();
  14055. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14056. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14057. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14058. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14059. return null;
  14060. }
  14061. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14062. };
  14063. /**
  14064. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14065. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14066. * 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.
  14067. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14068. * 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.
  14069. */
  14070. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14071. if (checkFace === void 0) { checkFace = false; }
  14072. if (facing === void 0) { facing = true; }
  14073. var world = this.getWorldMatrix();
  14074. var invMat = BABYLON.Tmp.Matrix[5];
  14075. world.invertToRef(invMat);
  14076. var invVect = BABYLON.Tmp.Vector3[8];
  14077. var closest = null;
  14078. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14079. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14080. if (projected) {
  14081. // tranform the local computed projected vector to world coordinates
  14082. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14083. }
  14084. return closest;
  14085. };
  14086. /**
  14087. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14088. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14089. * 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.
  14090. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14091. * 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.
  14092. */
  14093. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14094. if (checkFace === void 0) { checkFace = false; }
  14095. if (facing === void 0) { facing = true; }
  14096. var closest = null;
  14097. var tmpx = 0.0;
  14098. var tmpy = 0.0;
  14099. var tmpz = 0.0;
  14100. var d = 0.0; // tmp dot facet normal * facet position
  14101. var t0 = 0.0;
  14102. var projx = 0.0;
  14103. var projy = 0.0;
  14104. var projz = 0.0;
  14105. // Get all the facets in the same partitioning block than (x, y, z)
  14106. var facetPositions = this.getFacetLocalPositions();
  14107. var facetNormals = this.getFacetLocalNormals();
  14108. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14109. if (!facetsInBlock) {
  14110. return null;
  14111. }
  14112. // Get the closest facet to (x, y, z)
  14113. var shortest = Number.MAX_VALUE; // init distance vars
  14114. var tmpDistance = shortest;
  14115. var fib; // current facet in the block
  14116. var norm; // current facet normal
  14117. var p0; // current facet barycenter position
  14118. // loop on all the facets in the current partitioning block
  14119. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14120. fib = facetsInBlock[idx];
  14121. norm = facetNormals[fib];
  14122. p0 = facetPositions[fib];
  14123. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14124. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14125. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14126. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14127. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14128. projx = x + norm.x * t0;
  14129. projy = y + norm.y * t0;
  14130. projz = z + norm.z * t0;
  14131. tmpx = projx - x;
  14132. tmpy = projy - y;
  14133. tmpz = projz - z;
  14134. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14135. if (tmpDistance < shortest) {
  14136. shortest = tmpDistance;
  14137. closest = fib;
  14138. if (projected) {
  14139. projected.x = projx;
  14140. projected.y = projy;
  14141. projected.z = projz;
  14142. }
  14143. }
  14144. }
  14145. }
  14146. return closest;
  14147. };
  14148. /**
  14149. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14150. */
  14151. AbstractMesh.prototype.getFacetDataParameters = function () {
  14152. return this._facetParameters;
  14153. };
  14154. /**
  14155. * Disables the feature FacetData and frees the related memory.
  14156. * Returns the AbstractMesh.
  14157. */
  14158. AbstractMesh.prototype.disableFacetData = function () {
  14159. if (this._facetDataEnabled) {
  14160. this._facetDataEnabled = false;
  14161. this._facetPositions = null;
  14162. this._facetNormals = null;
  14163. this._facetPartitioning = null;
  14164. this._facetParameters = null;
  14165. }
  14166. return this;
  14167. };
  14168. /**
  14169. * Creates new normals data for the mesh.
  14170. * @param updatable.
  14171. */
  14172. AbstractMesh.prototype.createNormals = function (updatable) {
  14173. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14174. var indices = this.getIndices();
  14175. var normals;
  14176. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14177. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14178. }
  14179. else {
  14180. normals = [];
  14181. }
  14182. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14183. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14184. };
  14185. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14186. var engine = this.getEngine();
  14187. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14188. this._isOccluded = false;
  14189. return;
  14190. }
  14191. if (this.isOcclusionQueryInProgress) {
  14192. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14193. if (isOcclusionQueryAvailable) {
  14194. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14195. this._isOcclusionQueryInProgress = false;
  14196. this._occlusionInternalRetryCounter = 0;
  14197. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14198. }
  14199. else {
  14200. this._occlusionInternalRetryCounter++;
  14201. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14202. this._isOcclusionQueryInProgress = false;
  14203. this._occlusionInternalRetryCounter = 0;
  14204. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14205. // if strict continue the last state of the object.
  14206. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14207. }
  14208. else {
  14209. return;
  14210. }
  14211. }
  14212. }
  14213. var scene = this.getScene();
  14214. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14215. if (!this._occlusionQuery) {
  14216. this._occlusionQuery = engine.createQuery();
  14217. }
  14218. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14219. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14220. engine.endQuery(this.occlusionQueryAlgorithmType);
  14221. this._isOcclusionQueryInProgress = true;
  14222. };
  14223. // Statics
  14224. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14225. AbstractMesh._BILLBOARDMODE_X = 1;
  14226. AbstractMesh._BILLBOARDMODE_Y = 2;
  14227. AbstractMesh._BILLBOARDMODE_Z = 4;
  14228. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14229. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14230. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14231. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14232. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14233. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14234. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14235. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14236. return AbstractMesh;
  14237. }(BABYLON.Node));
  14238. BABYLON.AbstractMesh = AbstractMesh;
  14239. })(BABYLON || (BABYLON = {}));
  14240. //# sourceMappingURL=babylon.abstractMesh.js.map
  14241. var BABYLON;
  14242. (function (BABYLON) {
  14243. var Light = (function (_super) {
  14244. __extends(Light, _super);
  14245. /**
  14246. * Creates a Light object in the scene.
  14247. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14248. */
  14249. function Light(name, scene) {
  14250. var _this = _super.call(this, name, scene) || this;
  14251. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14252. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14253. _this.intensity = 1.0;
  14254. _this.range = Number.MAX_VALUE;
  14255. /**
  14256. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14257. * of light.
  14258. */
  14259. _this._photometricScale = 1.0;
  14260. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14261. _this._radius = 0.00001;
  14262. _this.renderPriority = 0;
  14263. /**
  14264. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14265. * the current shadow generator.
  14266. */
  14267. _this.shadowEnabled = true;
  14268. _this._excludeWithLayerMask = 0;
  14269. _this._includeOnlyWithLayerMask = 0;
  14270. _this._lightmapMode = 0;
  14271. _this._excludedMeshesIds = new Array();
  14272. _this._includedOnlyMeshesIds = new Array();
  14273. _this.getScene().addLight(_this);
  14274. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14275. _this._buildUniformLayout();
  14276. _this.includedOnlyMeshes = new Array();
  14277. _this.excludedMeshes = new Array();
  14278. _this._resyncMeshes();
  14279. return _this;
  14280. }
  14281. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14282. /**
  14283. * If every light affecting the material is in this lightmapMode,
  14284. * material.lightmapTexture adds or multiplies
  14285. * (depends on material.useLightmapAsShadowmap)
  14286. * after every other light calculations.
  14287. */
  14288. get: function () {
  14289. return Light._LIGHTMAP_DEFAULT;
  14290. },
  14291. enumerable: true,
  14292. configurable: true
  14293. });
  14294. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14295. /**
  14296. * material.lightmapTexture as only diffuse lighting from this light
  14297. * adds pnly specular lighting from this light
  14298. * adds dynamic shadows
  14299. */
  14300. get: function () {
  14301. return Light._LIGHTMAP_SPECULAR;
  14302. },
  14303. enumerable: true,
  14304. configurable: true
  14305. });
  14306. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14307. /**
  14308. * material.lightmapTexture as only lighting
  14309. * no light calculation from this light
  14310. * only adds dynamic shadows from this light
  14311. */
  14312. get: function () {
  14313. return Light._LIGHTMAP_SHADOWSONLY;
  14314. },
  14315. enumerable: true,
  14316. configurable: true
  14317. });
  14318. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14319. /**
  14320. * Each light type uses the default quantity according to its type:
  14321. * point/spot lights use luminous intensity
  14322. * directional lights use illuminance
  14323. */
  14324. get: function () {
  14325. return Light._INTENSITYMODE_AUTOMATIC;
  14326. },
  14327. enumerable: true,
  14328. configurable: true
  14329. });
  14330. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14331. /**
  14332. * lumen (lm)
  14333. */
  14334. get: function () {
  14335. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14336. },
  14337. enumerable: true,
  14338. configurable: true
  14339. });
  14340. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14341. /**
  14342. * candela (lm/sr)
  14343. */
  14344. get: function () {
  14345. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14346. },
  14347. enumerable: true,
  14348. configurable: true
  14349. });
  14350. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14351. /**
  14352. * lux (lm/m^2)
  14353. */
  14354. get: function () {
  14355. return Light._INTENSITYMODE_ILLUMINANCE;
  14356. },
  14357. enumerable: true,
  14358. configurable: true
  14359. });
  14360. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14361. /**
  14362. * nit (cd/m^2)
  14363. */
  14364. get: function () {
  14365. return Light._INTENSITYMODE_LUMINANCE;
  14366. },
  14367. enumerable: true,
  14368. configurable: true
  14369. });
  14370. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14371. /**
  14372. * Light type const id of the point light.
  14373. */
  14374. get: function () {
  14375. return Light._LIGHTTYPEID_POINTLIGHT;
  14376. },
  14377. enumerable: true,
  14378. configurable: true
  14379. });
  14380. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14381. /**
  14382. * Light type const id of the directional light.
  14383. */
  14384. get: function () {
  14385. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14386. },
  14387. enumerable: true,
  14388. configurable: true
  14389. });
  14390. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14391. /**
  14392. * Light type const id of the spot light.
  14393. */
  14394. get: function () {
  14395. return Light._LIGHTTYPEID_SPOTLIGHT;
  14396. },
  14397. enumerable: true,
  14398. configurable: true
  14399. });
  14400. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14401. /**
  14402. * Light type const id of the hemispheric light.
  14403. */
  14404. get: function () {
  14405. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14406. },
  14407. enumerable: true,
  14408. configurable: true
  14409. });
  14410. Object.defineProperty(Light.prototype, "intensityMode", {
  14411. /**
  14412. * Gets the photometric scale used to interpret the intensity.
  14413. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14414. */
  14415. get: function () {
  14416. return this._intensityMode;
  14417. },
  14418. /**
  14419. * Sets the photometric scale used to interpret the intensity.
  14420. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14421. */
  14422. set: function (value) {
  14423. this._intensityMode = value;
  14424. this._computePhotometricScale();
  14425. },
  14426. enumerable: true,
  14427. configurable: true
  14428. });
  14429. ;
  14430. ;
  14431. Object.defineProperty(Light.prototype, "radius", {
  14432. /**
  14433. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14434. */
  14435. get: function () {
  14436. return this._radius;
  14437. },
  14438. /**
  14439. * sets the light radius used by PBR Materials to simulate soft area lights.
  14440. */
  14441. set: function (value) {
  14442. this._radius = value;
  14443. this._computePhotometricScale();
  14444. },
  14445. enumerable: true,
  14446. configurable: true
  14447. });
  14448. ;
  14449. ;
  14450. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14451. get: function () {
  14452. return this._includedOnlyMeshes;
  14453. },
  14454. set: function (value) {
  14455. this._includedOnlyMeshes = value;
  14456. this._hookArrayForIncludedOnly(value);
  14457. },
  14458. enumerable: true,
  14459. configurable: true
  14460. });
  14461. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14462. get: function () {
  14463. return this._excludedMeshes;
  14464. },
  14465. set: function (value) {
  14466. this._excludedMeshes = value;
  14467. this._hookArrayForExcluded(value);
  14468. },
  14469. enumerable: true,
  14470. configurable: true
  14471. });
  14472. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14473. get: function () {
  14474. return this._excludeWithLayerMask;
  14475. },
  14476. set: function (value) {
  14477. this._excludeWithLayerMask = value;
  14478. this._resyncMeshes();
  14479. },
  14480. enumerable: true,
  14481. configurable: true
  14482. });
  14483. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14484. get: function () {
  14485. return this._includeOnlyWithLayerMask;
  14486. },
  14487. set: function (value) {
  14488. this._includeOnlyWithLayerMask = value;
  14489. this._resyncMeshes();
  14490. },
  14491. enumerable: true,
  14492. configurable: true
  14493. });
  14494. Object.defineProperty(Light.prototype, "lightmapMode", {
  14495. get: function () {
  14496. return this._lightmapMode;
  14497. },
  14498. set: function (value) {
  14499. if (this._lightmapMode === value) {
  14500. return;
  14501. }
  14502. this._lightmapMode = value;
  14503. this._markMeshesAsLightDirty();
  14504. },
  14505. enumerable: true,
  14506. configurable: true
  14507. });
  14508. Light.prototype._buildUniformLayout = function () {
  14509. // Overridden
  14510. };
  14511. /**
  14512. * Returns the string "Light".
  14513. */
  14514. Light.prototype.getClassName = function () {
  14515. return "Light";
  14516. };
  14517. /**
  14518. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14519. */
  14520. Light.prototype.toString = function (fullDetails) {
  14521. var ret = "Name: " + this.name;
  14522. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14523. if (this.animations) {
  14524. for (var i = 0; i < this.animations.length; i++) {
  14525. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14526. }
  14527. }
  14528. if (fullDetails) {
  14529. }
  14530. return ret;
  14531. };
  14532. /**
  14533. * Set the enabled state of this node.
  14534. * @param {boolean} value - the new enabled state
  14535. * @see isEnabled
  14536. */
  14537. Light.prototype.setEnabled = function (value) {
  14538. _super.prototype.setEnabled.call(this, value);
  14539. this._resyncMeshes();
  14540. };
  14541. /**
  14542. * Returns the Light associated shadow generator.
  14543. */
  14544. Light.prototype.getShadowGenerator = function () {
  14545. return this._shadowGenerator;
  14546. };
  14547. /**
  14548. * Returns a Vector3, the absolute light position in the World.
  14549. */
  14550. Light.prototype.getAbsolutePosition = function () {
  14551. return BABYLON.Vector3.Zero();
  14552. };
  14553. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14554. };
  14555. Light.prototype._getWorldMatrix = function () {
  14556. return BABYLON.Matrix.Identity();
  14557. };
  14558. /**
  14559. * Boolean : True if the light will affect the passed mesh.
  14560. */
  14561. Light.prototype.canAffectMesh = function (mesh) {
  14562. if (!mesh) {
  14563. return true;
  14564. }
  14565. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14566. return false;
  14567. }
  14568. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14569. return false;
  14570. }
  14571. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14572. return false;
  14573. }
  14574. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14575. return false;
  14576. }
  14577. return true;
  14578. };
  14579. /**
  14580. * Returns the light World matrix.
  14581. */
  14582. Light.prototype.getWorldMatrix = function () {
  14583. this._currentRenderId = this.getScene().getRenderId();
  14584. var worldMatrix = this._getWorldMatrix();
  14585. if (this.parent && this.parent.getWorldMatrix) {
  14586. if (!this._parentedWorldMatrix) {
  14587. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14588. }
  14589. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14590. this._markSyncedWithParent();
  14591. return this._parentedWorldMatrix;
  14592. }
  14593. return worldMatrix;
  14594. };
  14595. /**
  14596. * Sort function to order lights for rendering.
  14597. * @param a First Light object to compare to second.
  14598. * @param b Second Light object to compare first.
  14599. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14600. */
  14601. Light.compareLightsPriority = function (a, b) {
  14602. //shadow-casting lights have priority over non-shadow-casting lights
  14603. //the renderPrioirty is a secondary sort criterion
  14604. if (a.shadowEnabled !== b.shadowEnabled) {
  14605. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14606. }
  14607. return b.renderPriority - a.renderPriority;
  14608. };
  14609. /**
  14610. * Disposes the light.
  14611. */
  14612. Light.prototype.dispose = function () {
  14613. if (this._shadowGenerator) {
  14614. this._shadowGenerator.dispose();
  14615. this._shadowGenerator = null;
  14616. }
  14617. // Animations
  14618. this.getScene().stopAnimation(this);
  14619. // Remove from meshes
  14620. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14621. var mesh = _a[_i];
  14622. mesh._removeLightSource(this);
  14623. }
  14624. this._uniformBuffer.dispose();
  14625. // Remove from scene
  14626. this.getScene().removeLight(this);
  14627. _super.prototype.dispose.call(this);
  14628. };
  14629. /**
  14630. * Returns the light type ID (integer).
  14631. */
  14632. Light.prototype.getTypeID = function () {
  14633. return 0;
  14634. };
  14635. /**
  14636. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14637. */
  14638. Light.prototype.getScaledIntensity = function () {
  14639. return this._photometricScale * this.intensity;
  14640. };
  14641. /**
  14642. * Returns a new Light object, named "name", from the current one.
  14643. */
  14644. Light.prototype.clone = function (name) {
  14645. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14646. };
  14647. /**
  14648. * Serializes the current light into a Serialization object.
  14649. * Returns the serialized object.
  14650. */
  14651. Light.prototype.serialize = function () {
  14652. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14653. // Type
  14654. serializationObject.type = this.getTypeID();
  14655. // Parent
  14656. if (this.parent) {
  14657. serializationObject.parentId = this.parent.id;
  14658. }
  14659. // Inclusion / exclusions
  14660. if (this.excludedMeshes.length > 0) {
  14661. serializationObject.excludedMeshesIds = [];
  14662. this.excludedMeshes.forEach(function (mesh) {
  14663. serializationObject.excludedMeshesIds.push(mesh.id);
  14664. });
  14665. }
  14666. if (this.includedOnlyMeshes.length > 0) {
  14667. serializationObject.includedOnlyMeshesIds = [];
  14668. this.includedOnlyMeshes.forEach(function (mesh) {
  14669. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14670. });
  14671. }
  14672. // Animations
  14673. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14674. serializationObject.ranges = this.serializeAnimationRanges();
  14675. return serializationObject;
  14676. };
  14677. /**
  14678. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14679. * This new light is named "name" and added to the passed scene.
  14680. */
  14681. Light.GetConstructorFromName = function (type, name, scene) {
  14682. switch (type) {
  14683. case 0:
  14684. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14685. case 1:
  14686. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14687. case 2:
  14688. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14689. case 3:
  14690. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14691. }
  14692. };
  14693. /**
  14694. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14695. */
  14696. Light.Parse = function (parsedLight, scene) {
  14697. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14698. // Inclusion / exclusions
  14699. if (parsedLight.excludedMeshesIds) {
  14700. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14701. }
  14702. if (parsedLight.includedOnlyMeshesIds) {
  14703. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14704. }
  14705. // Parent
  14706. if (parsedLight.parentId) {
  14707. light._waitingParentId = parsedLight.parentId;
  14708. }
  14709. // Animations
  14710. if (parsedLight.animations) {
  14711. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14712. var parsedAnimation = parsedLight.animations[animationIndex];
  14713. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14714. }
  14715. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14716. }
  14717. if (parsedLight.autoAnimate) {
  14718. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14719. }
  14720. return light;
  14721. };
  14722. Light.prototype._hookArrayForExcluded = function (array) {
  14723. var _this = this;
  14724. var oldPush = array.push;
  14725. array.push = function () {
  14726. var items = [];
  14727. for (var _i = 0; _i < arguments.length; _i++) {
  14728. items[_i] = arguments[_i];
  14729. }
  14730. var result = oldPush.apply(array, items);
  14731. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14732. var item = items_1[_a];
  14733. item._resyncLighSource(_this);
  14734. }
  14735. return result;
  14736. };
  14737. var oldSplice = array.splice;
  14738. array.splice = function (index, deleteCount) {
  14739. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14740. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14741. var item = deleted_1[_i];
  14742. item._resyncLighSource(_this);
  14743. }
  14744. return deleted;
  14745. };
  14746. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14747. var item = array_1[_i];
  14748. item._resyncLighSource(this);
  14749. }
  14750. };
  14751. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14752. var _this = this;
  14753. var oldPush = array.push;
  14754. array.push = function () {
  14755. var items = [];
  14756. for (var _i = 0; _i < arguments.length; _i++) {
  14757. items[_i] = arguments[_i];
  14758. }
  14759. var result = oldPush.apply(array, items);
  14760. _this._resyncMeshes();
  14761. return result;
  14762. };
  14763. var oldSplice = array.splice;
  14764. array.splice = function (index, deleteCount) {
  14765. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14766. _this._resyncMeshes();
  14767. return deleted;
  14768. };
  14769. this._resyncMeshes();
  14770. };
  14771. Light.prototype._resyncMeshes = function () {
  14772. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14773. var mesh = _a[_i];
  14774. mesh._resyncLighSource(this);
  14775. }
  14776. };
  14777. Light.prototype._markMeshesAsLightDirty = function () {
  14778. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14779. var mesh = _a[_i];
  14780. if (mesh._lightSources.indexOf(this) !== -1) {
  14781. mesh._markSubMeshesAsLightDirty();
  14782. }
  14783. }
  14784. };
  14785. /**
  14786. * Recomputes the cached photometric scale if needed.
  14787. */
  14788. Light.prototype._computePhotometricScale = function () {
  14789. this._photometricScale = this._getPhotometricScale();
  14790. this.getScene().resetCachedMaterial();
  14791. };
  14792. /**
  14793. * Returns the Photometric Scale according to the light type and intensity mode.
  14794. */
  14795. Light.prototype._getPhotometricScale = function () {
  14796. var photometricScale = 0.0;
  14797. var lightTypeID = this.getTypeID();
  14798. //get photometric mode
  14799. var photometricMode = this.intensityMode;
  14800. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14801. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14802. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14803. }
  14804. else {
  14805. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14806. }
  14807. }
  14808. //compute photometric scale
  14809. switch (lightTypeID) {
  14810. case Light.LIGHTTYPEID_POINTLIGHT:
  14811. case Light.LIGHTTYPEID_SPOTLIGHT:
  14812. switch (photometricMode) {
  14813. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14814. photometricScale = 1.0 / (4.0 * Math.PI);
  14815. break;
  14816. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14817. photometricScale = 1.0;
  14818. break;
  14819. case Light.INTENSITYMODE_LUMINANCE:
  14820. photometricScale = this.radius * this.radius;
  14821. break;
  14822. }
  14823. break;
  14824. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14825. switch (photometricMode) {
  14826. case Light.INTENSITYMODE_ILLUMINANCE:
  14827. photometricScale = 1.0;
  14828. break;
  14829. case Light.INTENSITYMODE_LUMINANCE:
  14830. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14831. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14832. var apexAngleRadians = this.radius;
  14833. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14834. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14835. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14836. photometricScale = solidAngle;
  14837. break;
  14838. }
  14839. break;
  14840. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14841. // No fall off in hemisperic light.
  14842. photometricScale = 1.0;
  14843. break;
  14844. }
  14845. return photometricScale;
  14846. };
  14847. Light.prototype._reorderLightsInScene = function () {
  14848. var scene = this.getScene();
  14849. if (this.renderPriority != 0) {
  14850. scene.requireLightSorting = true;
  14851. }
  14852. this.getScene().sortLightsByPriority();
  14853. };
  14854. //lightmapMode Consts
  14855. Light._LIGHTMAP_DEFAULT = 0;
  14856. Light._LIGHTMAP_SPECULAR = 1;
  14857. Light._LIGHTMAP_SHADOWSONLY = 2;
  14858. // Intensity Mode Consts
  14859. Light._INTENSITYMODE_AUTOMATIC = 0;
  14860. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14861. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14862. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14863. Light._INTENSITYMODE_LUMINANCE = 4;
  14864. // Light types ids const.
  14865. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14866. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14867. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14868. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14869. __decorate([
  14870. BABYLON.serializeAsColor3()
  14871. ], Light.prototype, "diffuse", void 0);
  14872. __decorate([
  14873. BABYLON.serializeAsColor3()
  14874. ], Light.prototype, "specular", void 0);
  14875. __decorate([
  14876. BABYLON.serialize()
  14877. ], Light.prototype, "intensity", void 0);
  14878. __decorate([
  14879. BABYLON.serialize()
  14880. ], Light.prototype, "range", void 0);
  14881. __decorate([
  14882. BABYLON.serialize()
  14883. ], Light.prototype, "intensityMode", null);
  14884. __decorate([
  14885. BABYLON.serialize()
  14886. ], Light.prototype, "radius", null);
  14887. __decorate([
  14888. BABYLON.serialize()
  14889. ], Light.prototype, "_renderPriority", void 0);
  14890. __decorate([
  14891. BABYLON.expandToProperty("_reorderLightsInScene")
  14892. ], Light.prototype, "renderPriority", void 0);
  14893. __decorate([
  14894. BABYLON.serialize()
  14895. ], Light.prototype, "shadowEnabled", void 0);
  14896. __decorate([
  14897. BABYLON.serialize("excludeWithLayerMask")
  14898. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14899. __decorate([
  14900. BABYLON.serialize("includeOnlyWithLayerMask")
  14901. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14902. __decorate([
  14903. BABYLON.serialize("lightmapMode")
  14904. ], Light.prototype, "_lightmapMode", void 0);
  14905. return Light;
  14906. }(BABYLON.Node));
  14907. BABYLON.Light = Light;
  14908. })(BABYLON || (BABYLON = {}));
  14909. //# sourceMappingURL=babylon.light.js.map
  14910. var BABYLON;
  14911. (function (BABYLON) {
  14912. var Camera = (function (_super) {
  14913. __extends(Camera, _super);
  14914. function Camera(name, position, scene) {
  14915. var _this = _super.call(this, name, scene) || this;
  14916. _this.upVector = BABYLON.Vector3.Up();
  14917. _this.orthoLeft = null;
  14918. _this.orthoRight = null;
  14919. _this.orthoBottom = null;
  14920. _this.orthoTop = null;
  14921. _this.fov = 0.8;
  14922. _this.minZ = 1;
  14923. _this.maxZ = 10000.0;
  14924. _this.inertia = 0.9;
  14925. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14926. _this.isIntermediate = false;
  14927. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14928. _this.layerMask = 0x0FFFFFFF;
  14929. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14930. // Camera rig members
  14931. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14932. _this._rigCameras = new Array();
  14933. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14934. _this.customRenderTargets = new Array();
  14935. // Observables
  14936. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14937. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14938. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  14939. // Cache
  14940. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14941. _this._projectionMatrix = new BABYLON.Matrix();
  14942. _this._doNotComputeProjectionMatrix = false;
  14943. _this._postProcesses = new Array();
  14944. _this._transformMatrix = BABYLON.Matrix.Zero();
  14945. _this._activeMeshes = new BABYLON.SmartArray(256);
  14946. _this._globalPosition = BABYLON.Vector3.Zero();
  14947. _this._refreshFrustumPlanes = true;
  14948. _this.getScene().addCamera(_this);
  14949. if (!_this.getScene().activeCamera) {
  14950. _this.getScene().activeCamera = _this;
  14951. }
  14952. _this.position = position;
  14953. return _this;
  14954. }
  14955. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  14956. get: function () {
  14957. return Camera._PERSPECTIVE_CAMERA;
  14958. },
  14959. enumerable: true,
  14960. configurable: true
  14961. });
  14962. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14963. get: function () {
  14964. return Camera._ORTHOGRAPHIC_CAMERA;
  14965. },
  14966. enumerable: true,
  14967. configurable: true
  14968. });
  14969. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14970. get: function () {
  14971. return Camera._FOVMODE_VERTICAL_FIXED;
  14972. },
  14973. enumerable: true,
  14974. configurable: true
  14975. });
  14976. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  14977. get: function () {
  14978. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14979. },
  14980. enumerable: true,
  14981. configurable: true
  14982. });
  14983. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14984. get: function () {
  14985. return Camera._RIG_MODE_NONE;
  14986. },
  14987. enumerable: true,
  14988. configurable: true
  14989. });
  14990. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14991. get: function () {
  14992. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14993. },
  14994. enumerable: true,
  14995. configurable: true
  14996. });
  14997. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14998. get: function () {
  14999. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15000. },
  15001. enumerable: true,
  15002. configurable: true
  15003. });
  15004. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15005. get: function () {
  15006. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15007. },
  15008. enumerable: true,
  15009. configurable: true
  15010. });
  15011. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15012. get: function () {
  15013. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15014. },
  15015. enumerable: true,
  15016. configurable: true
  15017. });
  15018. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15019. get: function () {
  15020. return Camera._RIG_MODE_VR;
  15021. },
  15022. enumerable: true,
  15023. configurable: true
  15024. });
  15025. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15026. get: function () {
  15027. return Camera._RIG_MODE_WEBVR;
  15028. },
  15029. enumerable: true,
  15030. configurable: true
  15031. });
  15032. /**
  15033. * Store current camera state (fov, position, etc..)
  15034. */
  15035. Camera.prototype.storeState = function () {
  15036. this._stateStored = true;
  15037. this._storedFov = this.fov;
  15038. return this;
  15039. };
  15040. /**
  15041. * Restored camera state. You must call storeState() first
  15042. */
  15043. Camera.prototype.restoreState = function () {
  15044. if (!this._stateStored) {
  15045. return false;
  15046. }
  15047. this.fov = this._storedFov;
  15048. return true;
  15049. };
  15050. Camera.prototype.getClassName = function () {
  15051. return "Camera";
  15052. };
  15053. /**
  15054. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15055. */
  15056. Camera.prototype.toString = function (fullDetails) {
  15057. var ret = "Name: " + this.name;
  15058. ret += ", type: " + this.getClassName();
  15059. if (this.animations) {
  15060. for (var i = 0; i < this.animations.length; i++) {
  15061. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15062. }
  15063. }
  15064. if (fullDetails) {
  15065. }
  15066. return ret;
  15067. };
  15068. Object.defineProperty(Camera.prototype, "globalPosition", {
  15069. get: function () {
  15070. return this._globalPosition;
  15071. },
  15072. enumerable: true,
  15073. configurable: true
  15074. });
  15075. Camera.prototype.getActiveMeshes = function () {
  15076. return this._activeMeshes;
  15077. };
  15078. Camera.prototype.isActiveMesh = function (mesh) {
  15079. return (this._activeMeshes.indexOf(mesh) !== -1);
  15080. };
  15081. //Cache
  15082. Camera.prototype._initCache = function () {
  15083. _super.prototype._initCache.call(this);
  15084. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15085. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15086. this._cache.mode = undefined;
  15087. this._cache.minZ = undefined;
  15088. this._cache.maxZ = undefined;
  15089. this._cache.fov = undefined;
  15090. this._cache.fovMode = undefined;
  15091. this._cache.aspectRatio = undefined;
  15092. this._cache.orthoLeft = undefined;
  15093. this._cache.orthoRight = undefined;
  15094. this._cache.orthoBottom = undefined;
  15095. this._cache.orthoTop = undefined;
  15096. this._cache.renderWidth = undefined;
  15097. this._cache.renderHeight = undefined;
  15098. };
  15099. Camera.prototype._updateCache = function (ignoreParentClass) {
  15100. if (!ignoreParentClass) {
  15101. _super.prototype._updateCache.call(this);
  15102. }
  15103. var engine = this.getEngine();
  15104. this._cache.position.copyFrom(this.position);
  15105. this._cache.upVector.copyFrom(this.upVector);
  15106. this._cache.mode = this.mode;
  15107. this._cache.minZ = this.minZ;
  15108. this._cache.maxZ = this.maxZ;
  15109. this._cache.fov = this.fov;
  15110. this._cache.fovMode = this.fovMode;
  15111. this._cache.aspectRatio = engine.getAspectRatio(this);
  15112. this._cache.orthoLeft = this.orthoLeft;
  15113. this._cache.orthoRight = this.orthoRight;
  15114. this._cache.orthoBottom = this.orthoBottom;
  15115. this._cache.orthoTop = this.orthoTop;
  15116. this._cache.renderWidth = engine.getRenderWidth();
  15117. this._cache.renderHeight = engine.getRenderHeight();
  15118. };
  15119. Camera.prototype._updateFromScene = function () {
  15120. this.updateCache();
  15121. this.update();
  15122. };
  15123. // Synchronized
  15124. Camera.prototype._isSynchronized = function () {
  15125. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15126. };
  15127. Camera.prototype._isSynchronizedViewMatrix = function () {
  15128. if (!_super.prototype._isSynchronized.call(this))
  15129. return false;
  15130. return this._cache.position.equals(this.position)
  15131. && this._cache.upVector.equals(this.upVector)
  15132. && this.isSynchronizedWithParent();
  15133. };
  15134. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15135. var check = this._cache.mode === this.mode
  15136. && this._cache.minZ === this.minZ
  15137. && this._cache.maxZ === this.maxZ;
  15138. if (!check) {
  15139. return false;
  15140. }
  15141. var engine = this.getEngine();
  15142. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15143. check = this._cache.fov === this.fov
  15144. && this._cache.fovMode === this.fovMode
  15145. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15146. }
  15147. else {
  15148. check = this._cache.orthoLeft === this.orthoLeft
  15149. && this._cache.orthoRight === this.orthoRight
  15150. && this._cache.orthoBottom === this.orthoBottom
  15151. && this._cache.orthoTop === this.orthoTop
  15152. && this._cache.renderWidth === engine.getRenderWidth()
  15153. && this._cache.renderHeight === engine.getRenderHeight();
  15154. }
  15155. return check;
  15156. };
  15157. // Controls
  15158. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15159. };
  15160. Camera.prototype.detachControl = function (element) {
  15161. };
  15162. Camera.prototype.update = function () {
  15163. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15164. this._updateRigCameras();
  15165. }
  15166. this._checkInputs();
  15167. };
  15168. Camera.prototype._checkInputs = function () {
  15169. this.onAfterCheckInputsObservable.notifyObservers(this);
  15170. };
  15171. Object.defineProperty(Camera.prototype, "rigCameras", {
  15172. get: function () {
  15173. return this._rigCameras;
  15174. },
  15175. enumerable: true,
  15176. configurable: true
  15177. });
  15178. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15179. get: function () {
  15180. return this._rigPostProcess;
  15181. },
  15182. enumerable: true,
  15183. configurable: true
  15184. });
  15185. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15186. // invalidate framebuffer
  15187. if (this._postProcesses.length > 0) {
  15188. this._postProcesses[0].markTextureDirty();
  15189. }
  15190. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15191. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15192. var cam = this._rigCameras[i];
  15193. var rigPostProcess = cam._rigPostProcess;
  15194. // for VR rig, there does not have to be a post process
  15195. if (rigPostProcess) {
  15196. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15197. if (isPass) {
  15198. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15199. cam.isIntermediate = this._postProcesses.length === 0;
  15200. }
  15201. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15202. rigPostProcess.markTextureDirty();
  15203. }
  15204. else {
  15205. cam._postProcesses = this._postProcesses.slice(0);
  15206. }
  15207. }
  15208. };
  15209. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15210. if (insertAt === void 0) { insertAt = null; }
  15211. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15212. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15213. return 0;
  15214. }
  15215. if (insertAt == null || insertAt < 0) {
  15216. this._postProcesses.push(postProcess);
  15217. }
  15218. else {
  15219. this._postProcesses.splice(insertAt, 0, postProcess);
  15220. }
  15221. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15222. return this._postProcesses.indexOf(postProcess);
  15223. };
  15224. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15225. if (atIndices === void 0) { atIndices = null; }
  15226. var result = [];
  15227. var i;
  15228. var index;
  15229. if (!atIndices) {
  15230. var idx = this._postProcesses.indexOf(postProcess);
  15231. if (idx !== -1) {
  15232. this._postProcesses.splice(idx, 1);
  15233. }
  15234. }
  15235. else {
  15236. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15237. // iterate descending, so can just splice as we go
  15238. for (i = atIndices.length - 1; i >= 0; i--) {
  15239. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15240. result.push(i);
  15241. continue;
  15242. }
  15243. index = atIndices[i];
  15244. this._postProcesses.splice(index, 1);
  15245. }
  15246. }
  15247. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15248. return result;
  15249. };
  15250. Camera.prototype.getWorldMatrix = function () {
  15251. if (!this._worldMatrix) {
  15252. this._worldMatrix = BABYLON.Matrix.Identity();
  15253. }
  15254. var viewMatrix = this.getViewMatrix();
  15255. viewMatrix.invertToRef(this._worldMatrix);
  15256. return this._worldMatrix;
  15257. };
  15258. Camera.prototype._getViewMatrix = function () {
  15259. return BABYLON.Matrix.Identity();
  15260. };
  15261. Camera.prototype.getViewMatrix = function (force) {
  15262. if (!force && this._isSynchronizedViewMatrix()) {
  15263. return this._computedViewMatrix;
  15264. }
  15265. this._computedViewMatrix = this._getViewMatrix();
  15266. this._currentRenderId = this.getScene().getRenderId();
  15267. this._refreshFrustumPlanes = true;
  15268. if (!this.parent || !this.parent.getWorldMatrix) {
  15269. this._globalPosition.copyFrom(this.position);
  15270. }
  15271. else {
  15272. if (!this._worldMatrix) {
  15273. this._worldMatrix = BABYLON.Matrix.Identity();
  15274. }
  15275. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15276. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15277. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15278. this._computedViewMatrix.invert();
  15279. this._markSyncedWithParent();
  15280. }
  15281. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15282. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15283. }
  15284. this.onViewMatrixChangedObservable.notifyObservers(this);
  15285. return this._computedViewMatrix;
  15286. };
  15287. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15288. this._doNotComputeProjectionMatrix = true;
  15289. if (projection !== undefined) {
  15290. this._projectionMatrix = projection;
  15291. }
  15292. };
  15293. ;
  15294. Camera.prototype.unfreezeProjectionMatrix = function () {
  15295. this._doNotComputeProjectionMatrix = false;
  15296. };
  15297. ;
  15298. Camera.prototype.getProjectionMatrix = function (force) {
  15299. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15300. return this._projectionMatrix;
  15301. }
  15302. this._refreshFrustumPlanes = true;
  15303. var engine = this.getEngine();
  15304. var scene = this.getScene();
  15305. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15306. if (this.minZ <= 0) {
  15307. this.minZ = 0.1;
  15308. }
  15309. if (scene.useRightHandedSystem) {
  15310. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15311. }
  15312. else {
  15313. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15314. }
  15315. }
  15316. else {
  15317. var halfWidth = engine.getRenderWidth() / 2.0;
  15318. var halfHeight = engine.getRenderHeight() / 2.0;
  15319. if (scene.useRightHandedSystem) {
  15320. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15321. }
  15322. else {
  15323. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15324. }
  15325. }
  15326. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15327. return this._projectionMatrix;
  15328. };
  15329. Camera.prototype.getTranformationMatrix = function () {
  15330. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15331. return this._transformMatrix;
  15332. };
  15333. Camera.prototype.updateFrustumPlanes = function () {
  15334. if (!this._refreshFrustumPlanes) {
  15335. return;
  15336. }
  15337. this.getTranformationMatrix();
  15338. if (!this._frustumPlanes) {
  15339. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15340. }
  15341. else {
  15342. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15343. }
  15344. this._refreshFrustumPlanes = false;
  15345. };
  15346. Camera.prototype.isInFrustum = function (target) {
  15347. this.updateFrustumPlanes();
  15348. return target.isInFrustum(this._frustumPlanes);
  15349. };
  15350. Camera.prototype.isCompletelyInFrustum = function (target) {
  15351. this.updateFrustumPlanes();
  15352. return target.isCompletelyInFrustum(this._frustumPlanes);
  15353. };
  15354. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15355. if (length === void 0) { length = 100; }
  15356. if (!transform) {
  15357. transform = this.getWorldMatrix();
  15358. }
  15359. if (!origin) {
  15360. origin = this.position;
  15361. }
  15362. var forward = new BABYLON.Vector3(0, 0, 1);
  15363. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15364. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15365. return new BABYLON.Ray(origin, direction, length);
  15366. };
  15367. Camera.prototype.dispose = function () {
  15368. // Observables
  15369. this.onViewMatrixChangedObservable.clear();
  15370. this.onProjectionMatrixChangedObservable.clear();
  15371. this.onAfterCheckInputsObservable.clear();
  15372. // Inputs
  15373. if (this.inputs) {
  15374. this.inputs.clear();
  15375. }
  15376. // Animations
  15377. this.getScene().stopAnimation(this);
  15378. // Remove from scene
  15379. this.getScene().removeCamera(this);
  15380. while (this._rigCameras.length > 0) {
  15381. this._rigCameras.pop().dispose();
  15382. }
  15383. // Postprocesses
  15384. var i = this._postProcesses.length;
  15385. while (--i >= 0) {
  15386. this._postProcesses[i].dispose(this);
  15387. }
  15388. // Render targets
  15389. var i = this.customRenderTargets.length;
  15390. while (--i >= 0) {
  15391. this.customRenderTargets[i].dispose();
  15392. }
  15393. this.customRenderTargets = [];
  15394. // Active Meshes
  15395. this._activeMeshes.dispose();
  15396. _super.prototype.dispose.call(this);
  15397. };
  15398. Object.defineProperty(Camera.prototype, "leftCamera", {
  15399. // ---- Camera rigs section ----
  15400. get: function () {
  15401. if (this._rigCameras.length < 1) {
  15402. return undefined;
  15403. }
  15404. return this._rigCameras[0];
  15405. },
  15406. enumerable: true,
  15407. configurable: true
  15408. });
  15409. Object.defineProperty(Camera.prototype, "rightCamera", {
  15410. get: function () {
  15411. if (this._rigCameras.length < 2) {
  15412. return undefined;
  15413. }
  15414. return this._rigCameras[1];
  15415. },
  15416. enumerable: true,
  15417. configurable: true
  15418. });
  15419. Camera.prototype.getLeftTarget = function () {
  15420. if (this._rigCameras.length < 1) {
  15421. return undefined;
  15422. }
  15423. return this._rigCameras[0].getTarget();
  15424. };
  15425. Camera.prototype.getRightTarget = function () {
  15426. if (this._rigCameras.length < 2) {
  15427. return undefined;
  15428. }
  15429. return this._rigCameras[1].getTarget();
  15430. };
  15431. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15432. while (this._rigCameras.length > 0) {
  15433. this._rigCameras.pop().dispose();
  15434. }
  15435. this.cameraRigMode = mode;
  15436. this._cameraRigParams = {};
  15437. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15438. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15439. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15440. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15441. // create the rig cameras, unless none
  15442. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15443. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15444. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15445. }
  15446. switch (this.cameraRigMode) {
  15447. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15448. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15449. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15450. break;
  15451. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15452. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15453. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15454. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15455. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15456. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15457. break;
  15458. case Camera.RIG_MODE_VR:
  15459. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15460. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15461. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15462. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15463. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15464. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15465. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15466. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15467. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15468. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15469. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15470. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15471. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15472. if (metrics.compensateDistortion) {
  15473. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15474. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15475. }
  15476. break;
  15477. case Camera.RIG_MODE_WEBVR:
  15478. if (rigParams.vrDisplay) {
  15479. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15480. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15481. //Left eye
  15482. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15483. this._rigCameras[0].setCameraRigParameter("left", true);
  15484. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15485. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15486. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15487. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15488. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15489. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15490. this._rigCameras[0].parent = this;
  15491. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15492. //Right eye
  15493. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15494. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15495. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15496. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15497. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15498. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15499. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15500. this._rigCameras[1].parent = this;
  15501. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15502. }
  15503. break;
  15504. }
  15505. this._cascadePostProcessesToRigCams();
  15506. this.
  15507. update();
  15508. };
  15509. Camera.prototype._getVRProjectionMatrix = function () {
  15510. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15511. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15512. return this._projectionMatrix;
  15513. };
  15514. Camera.prototype._updateCameraRotationMatrix = function () {
  15515. //Here for WebVR
  15516. };
  15517. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15518. //Here for WebVR
  15519. };
  15520. /**
  15521. * This function MUST be overwritten by the different WebVR cameras available.
  15522. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15523. */
  15524. Camera.prototype._getWebVRProjectionMatrix = function () {
  15525. return BABYLON.Matrix.Identity();
  15526. };
  15527. /**
  15528. * This function MUST be overwritten by the different WebVR cameras available.
  15529. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15530. */
  15531. Camera.prototype._getWebVRViewMatrix = function () {
  15532. return BABYLON.Matrix.Identity();
  15533. };
  15534. Camera.prototype.setCameraRigParameter = function (name, value) {
  15535. if (!this._cameraRigParams) {
  15536. this._cameraRigParams = {};
  15537. }
  15538. this._cameraRigParams[name] = value;
  15539. //provisionnally:
  15540. if (name === "interaxialDistance") {
  15541. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15542. }
  15543. };
  15544. /**
  15545. * needs to be overridden by children so sub has required properties to be copied
  15546. */
  15547. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15548. return null;
  15549. };
  15550. /**
  15551. * May need to be overridden by children
  15552. */
  15553. Camera.prototype._updateRigCameras = function () {
  15554. for (var i = 0; i < this._rigCameras.length; i++) {
  15555. this._rigCameras[i].minZ = this.minZ;
  15556. this._rigCameras[i].maxZ = this.maxZ;
  15557. this._rigCameras[i].fov = this.fov;
  15558. }
  15559. // only update viewport when ANAGLYPH
  15560. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15561. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15562. }
  15563. };
  15564. Camera.prototype._setupInputs = function () {
  15565. };
  15566. Camera.prototype.serialize = function () {
  15567. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15568. // Type
  15569. serializationObject.type = this.getClassName();
  15570. // Parent
  15571. if (this.parent) {
  15572. serializationObject.parentId = this.parent.id;
  15573. }
  15574. if (this.inputs) {
  15575. this.inputs.serialize(serializationObject);
  15576. }
  15577. // Animations
  15578. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15579. serializationObject.ranges = this.serializeAnimationRanges();
  15580. return serializationObject;
  15581. };
  15582. Camera.prototype.clone = function (name) {
  15583. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15584. };
  15585. Camera.prototype.getDirection = function (localAxis) {
  15586. var result = BABYLON.Vector3.Zero();
  15587. this.getDirectionToRef(localAxis, result);
  15588. return result;
  15589. };
  15590. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15591. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15592. };
  15593. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15594. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15595. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15596. switch (type) {
  15597. case "ArcRotateCamera":
  15598. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15599. case "DeviceOrientationCamera":
  15600. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15601. case "FollowCamera":
  15602. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15603. case "ArcFollowCamera":
  15604. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15605. case "GamepadCamera":
  15606. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15607. case "TouchCamera":
  15608. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15609. case "VirtualJoysticksCamera":
  15610. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15611. case "WebVRFreeCamera":
  15612. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15613. case "WebVRGamepadCamera":
  15614. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15615. case "VRDeviceOrientationFreeCamera":
  15616. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15617. case "VRDeviceOrientationGamepadCamera":
  15618. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15619. case "AnaglyphArcRotateCamera":
  15620. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15621. case "AnaglyphFreeCamera":
  15622. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15623. case "AnaglyphGamepadCamera":
  15624. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15625. case "AnaglyphUniversalCamera":
  15626. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15627. case "StereoscopicArcRotateCamera":
  15628. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15629. case "StereoscopicFreeCamera":
  15630. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15631. case "StereoscopicGamepadCamera":
  15632. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15633. case "StereoscopicUniversalCamera":
  15634. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15635. case "FreeCamera":// Forcing Universal here
  15636. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15637. default:// Universal Camera is the default value
  15638. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15639. }
  15640. };
  15641. Camera.Parse = function (parsedCamera, scene) {
  15642. var type = parsedCamera.type;
  15643. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15644. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15645. // Parent
  15646. if (parsedCamera.parentId) {
  15647. camera._waitingParentId = parsedCamera.parentId;
  15648. }
  15649. //If camera has an input manager, let it parse inputs settings
  15650. if (camera.inputs) {
  15651. camera.inputs.parse(parsedCamera);
  15652. camera._setupInputs();
  15653. }
  15654. if (camera.setPosition) {
  15655. camera.position.copyFromFloats(0, 0, 0);
  15656. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15657. }
  15658. // Target
  15659. if (parsedCamera.target) {
  15660. if (camera.setTarget) {
  15661. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15662. }
  15663. }
  15664. // Apply 3d rig, when found
  15665. if (parsedCamera.cameraRigMode) {
  15666. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15667. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15668. }
  15669. // Animations
  15670. if (parsedCamera.animations) {
  15671. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15672. var parsedAnimation = parsedCamera.animations[animationIndex];
  15673. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15674. }
  15675. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15676. }
  15677. if (parsedCamera.autoAnimate) {
  15678. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15679. }
  15680. return camera;
  15681. };
  15682. // Statics
  15683. Camera._PERSPECTIVE_CAMERA = 0;
  15684. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15685. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15686. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15687. Camera._RIG_MODE_NONE = 0;
  15688. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15689. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15690. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15691. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15692. Camera._RIG_MODE_VR = 20;
  15693. Camera._RIG_MODE_WEBVR = 21;
  15694. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15695. __decorate([
  15696. BABYLON.serializeAsVector3()
  15697. ], Camera.prototype, "position", void 0);
  15698. __decorate([
  15699. BABYLON.serializeAsVector3()
  15700. ], Camera.prototype, "upVector", void 0);
  15701. __decorate([
  15702. BABYLON.serialize()
  15703. ], Camera.prototype, "orthoLeft", void 0);
  15704. __decorate([
  15705. BABYLON.serialize()
  15706. ], Camera.prototype, "orthoRight", void 0);
  15707. __decorate([
  15708. BABYLON.serialize()
  15709. ], Camera.prototype, "orthoBottom", void 0);
  15710. __decorate([
  15711. BABYLON.serialize()
  15712. ], Camera.prototype, "orthoTop", void 0);
  15713. __decorate([
  15714. BABYLON.serialize()
  15715. ], Camera.prototype, "fov", void 0);
  15716. __decorate([
  15717. BABYLON.serialize()
  15718. ], Camera.prototype, "minZ", void 0);
  15719. __decorate([
  15720. BABYLON.serialize()
  15721. ], Camera.prototype, "maxZ", void 0);
  15722. __decorate([
  15723. BABYLON.serialize()
  15724. ], Camera.prototype, "inertia", void 0);
  15725. __decorate([
  15726. BABYLON.serialize()
  15727. ], Camera.prototype, "mode", void 0);
  15728. __decorate([
  15729. BABYLON.serialize()
  15730. ], Camera.prototype, "layerMask", void 0);
  15731. __decorate([
  15732. BABYLON.serialize()
  15733. ], Camera.prototype, "fovMode", void 0);
  15734. __decorate([
  15735. BABYLON.serialize()
  15736. ], Camera.prototype, "cameraRigMode", void 0);
  15737. __decorate([
  15738. BABYLON.serialize()
  15739. ], Camera.prototype, "interaxialDistance", void 0);
  15740. __decorate([
  15741. BABYLON.serialize()
  15742. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15743. return Camera;
  15744. }(BABYLON.Node));
  15745. BABYLON.Camera = Camera;
  15746. })(BABYLON || (BABYLON = {}));
  15747. //# sourceMappingURL=babylon.camera.js.map
  15748. var BABYLON;
  15749. (function (BABYLON) {
  15750. var RenderingManager = (function () {
  15751. function RenderingManager(scene) {
  15752. this._renderingGroups = new Array();
  15753. this._autoClearDepthStencil = {};
  15754. this._customOpaqueSortCompareFn = {};
  15755. this._customAlphaTestSortCompareFn = {};
  15756. this._customTransparentSortCompareFn = {};
  15757. this._renderinGroupInfo = null;
  15758. this._scene = scene;
  15759. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15760. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15761. }
  15762. }
  15763. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15764. if (depth === void 0) { depth = true; }
  15765. if (stencil === void 0) { stencil = true; }
  15766. if (this._depthStencilBufferAlreadyCleaned) {
  15767. return;
  15768. }
  15769. this._scene.getEngine().clear(null, false, depth, stencil);
  15770. this._depthStencilBufferAlreadyCleaned = true;
  15771. };
  15772. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15773. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15774. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15775. var info = null;
  15776. if (observable) {
  15777. if (!this._renderinGroupInfo) {
  15778. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15779. }
  15780. info = this._renderinGroupInfo;
  15781. info.scene = this._scene;
  15782. info.camera = this._scene.activeCamera;
  15783. }
  15784. // Dispatch sprites
  15785. if (renderSprites) {
  15786. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15787. var manager = this._scene.spriteManagers[index];
  15788. this.dispatchSprites(manager);
  15789. }
  15790. }
  15791. // Render
  15792. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15793. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15794. var renderingGroup = this._renderingGroups[index];
  15795. if (!renderingGroup && !observable)
  15796. continue;
  15797. this._currentIndex = index;
  15798. var renderingGroupMask = 0;
  15799. // Fire PRECLEAR stage
  15800. if (observable) {
  15801. renderingGroupMask = Math.pow(2, index);
  15802. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15803. info.renderingGroupId = index;
  15804. observable.notifyObservers(info, renderingGroupMask);
  15805. }
  15806. // Clear depth/stencil if needed
  15807. if (RenderingManager.AUTOCLEAR) {
  15808. var autoClear = this._autoClearDepthStencil[index];
  15809. if (autoClear && autoClear.autoClear) {
  15810. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15811. }
  15812. }
  15813. if (observable) {
  15814. // Fire PREOPAQUE stage
  15815. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15816. observable.notifyObservers(info, renderingGroupMask);
  15817. // Fire PRETRANSPARENT stage
  15818. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15819. observable.notifyObservers(info, renderingGroupMask);
  15820. }
  15821. if (renderingGroup)
  15822. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15823. // Fire POSTTRANSPARENT stage
  15824. if (observable) {
  15825. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15826. observable.notifyObservers(info, renderingGroupMask);
  15827. }
  15828. }
  15829. };
  15830. RenderingManager.prototype.reset = function () {
  15831. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15832. var renderingGroup = this._renderingGroups[index];
  15833. if (renderingGroup) {
  15834. renderingGroup.prepare();
  15835. }
  15836. }
  15837. };
  15838. RenderingManager.prototype.dispose = function () {
  15839. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15840. var renderingGroup = this._renderingGroups[index];
  15841. if (renderingGroup) {
  15842. renderingGroup.dispose();
  15843. }
  15844. }
  15845. this._renderingGroups.length = 0;
  15846. };
  15847. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15848. if (!this._renderingGroups[renderingGroupId]) {
  15849. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15850. }
  15851. };
  15852. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15853. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15854. this._prepareRenderingGroup(renderingGroupId);
  15855. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15856. };
  15857. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15858. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15859. this._prepareRenderingGroup(renderingGroupId);
  15860. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15861. };
  15862. RenderingManager.prototype.dispatch = function (subMesh) {
  15863. var mesh = subMesh.getMesh();
  15864. var renderingGroupId = mesh.renderingGroupId || 0;
  15865. this._prepareRenderingGroup(renderingGroupId);
  15866. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15867. };
  15868. /**
  15869. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15870. * This allowed control for front to back rendering or reversly depending of the special needs.
  15871. *
  15872. * @param renderingGroupId The rendering group id corresponding to its index
  15873. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15874. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15875. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15876. */
  15877. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15878. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15879. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15880. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15881. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15882. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15883. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15884. if (this._renderingGroups[renderingGroupId]) {
  15885. var group = this._renderingGroups[renderingGroupId];
  15886. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15887. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15888. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15889. }
  15890. };
  15891. /**
  15892. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15893. *
  15894. * @param renderingGroupId The rendering group id corresponding to its index
  15895. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15896. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15897. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15898. */
  15899. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15900. if (depth === void 0) { depth = true; }
  15901. if (stencil === void 0) { stencil = true; }
  15902. this._autoClearDepthStencil[renderingGroupId] = {
  15903. autoClear: autoClearDepthStencil,
  15904. depth: depth,
  15905. stencil: stencil
  15906. };
  15907. };
  15908. /**
  15909. * The max id used for rendering groups (not included)
  15910. */
  15911. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15912. /**
  15913. * The min id used for rendering groups (included)
  15914. */
  15915. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15916. /**
  15917. * Used to globally prevent autoclearing scenes.
  15918. */
  15919. RenderingManager.AUTOCLEAR = true;
  15920. return RenderingManager;
  15921. }());
  15922. BABYLON.RenderingManager = RenderingManager;
  15923. })(BABYLON || (BABYLON = {}));
  15924. //# sourceMappingURL=babylon.renderingManager.js.map
  15925. var BABYLON;
  15926. (function (BABYLON) {
  15927. var RenderingGroup = (function () {
  15928. /**
  15929. * Creates a new rendering group.
  15930. * @param index The rendering group index
  15931. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15932. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15933. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15934. */
  15935. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15936. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15937. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15938. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15939. this.index = index;
  15940. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15941. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15942. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15943. this._particleSystems = new BABYLON.SmartArray(256);
  15944. this._spriteManagers = new BABYLON.SmartArray(256);
  15945. this._edgesRenderers = new BABYLON.SmartArray(16);
  15946. this._scene = scene;
  15947. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15948. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15949. this.transparentSortCompareFn = transparentSortCompareFn;
  15950. }
  15951. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15952. /**
  15953. * Set the opaque sort comparison function.
  15954. * If null the sub meshes will be render in the order they were created
  15955. */
  15956. set: function (value) {
  15957. this._opaqueSortCompareFn = value;
  15958. if (value) {
  15959. this._renderOpaque = this.renderOpaqueSorted;
  15960. }
  15961. else {
  15962. this._renderOpaque = RenderingGroup.renderUnsorted;
  15963. }
  15964. },
  15965. enumerable: true,
  15966. configurable: true
  15967. });
  15968. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15969. /**
  15970. * Set the alpha test sort comparison function.
  15971. * If null the sub meshes will be render in the order they were created
  15972. */
  15973. set: function (value) {
  15974. this._alphaTestSortCompareFn = value;
  15975. if (value) {
  15976. this._renderAlphaTest = this.renderAlphaTestSorted;
  15977. }
  15978. else {
  15979. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15980. }
  15981. },
  15982. enumerable: true,
  15983. configurable: true
  15984. });
  15985. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15986. /**
  15987. * Set the transparent sort comparison function.
  15988. * If null the sub meshes will be render in the order they were created
  15989. */
  15990. set: function (value) {
  15991. if (value) {
  15992. this._transparentSortCompareFn = value;
  15993. }
  15994. else {
  15995. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15996. }
  15997. this._renderTransparent = this.renderTransparentSorted;
  15998. },
  15999. enumerable: true,
  16000. configurable: true
  16001. });
  16002. /**
  16003. * Render all the sub meshes contained in the group.
  16004. * @param customRenderFunction Used to override the default render behaviour of the group.
  16005. * @returns true if rendered some submeshes.
  16006. */
  16007. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16008. if (customRenderFunction) {
  16009. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  16010. return;
  16011. }
  16012. var engine = this._scene.getEngine();
  16013. // Opaque
  16014. if (this._opaqueSubMeshes.length !== 0) {
  16015. this._renderOpaque(this._opaqueSubMeshes);
  16016. }
  16017. // Alpha test
  16018. if (this._alphaTestSubMeshes.length !== 0) {
  16019. engine.setAlphaTesting(true);
  16020. this._renderAlphaTest(this._alphaTestSubMeshes);
  16021. engine.setAlphaTesting(false);
  16022. }
  16023. var stencilState = engine.getStencilBuffer();
  16024. engine.setStencilBuffer(false);
  16025. // Sprites
  16026. if (renderSprites) {
  16027. this._renderSprites();
  16028. }
  16029. // Particles
  16030. if (renderParticles) {
  16031. this._renderParticles(activeMeshes);
  16032. }
  16033. if (this.onBeforeTransparentRendering) {
  16034. this.onBeforeTransparentRendering();
  16035. }
  16036. // Transparent
  16037. if (this._transparentSubMeshes.length !== 0) {
  16038. this._renderTransparent(this._transparentSubMeshes);
  16039. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16040. }
  16041. // Set back stencil to false in case it changes before the edge renderer.
  16042. engine.setStencilBuffer(false);
  16043. // Edges
  16044. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16045. this._edgesRenderers.data[edgesRendererIndex].render();
  16046. }
  16047. // Restore Stencil state.
  16048. engine.setStencilBuffer(stencilState);
  16049. };
  16050. /**
  16051. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16052. * @param subMeshes The submeshes to render
  16053. */
  16054. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16055. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16056. };
  16057. /**
  16058. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16059. * @param subMeshes The submeshes to render
  16060. */
  16061. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16062. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16063. };
  16064. /**
  16065. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16066. * @param subMeshes The submeshes to render
  16067. */
  16068. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16069. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16070. };
  16071. /**
  16072. * Renders the submeshes in a specified order.
  16073. * @param subMeshes The submeshes to sort before render
  16074. * @param sortCompareFn The comparison function use to sort
  16075. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16076. * @param transparent Specifies to activate blending if true
  16077. */
  16078. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16079. var subIndex = 0;
  16080. var subMesh;
  16081. for (; subIndex < subMeshes.length; subIndex++) {
  16082. subMesh = subMeshes.data[subIndex];
  16083. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16084. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16085. }
  16086. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16087. sortedArray.sort(sortCompareFn);
  16088. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16089. subMesh = sortedArray[subIndex];
  16090. subMesh.render(transparent);
  16091. }
  16092. };
  16093. /**
  16094. * Renders the submeshes in the order they were dispatched (no sort applied).
  16095. * @param subMeshes The submeshes to render
  16096. */
  16097. RenderingGroup.renderUnsorted = function (subMeshes) {
  16098. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16099. var submesh = subMeshes.data[subIndex];
  16100. submesh.render(false);
  16101. }
  16102. };
  16103. /**
  16104. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16105. * are rendered back to front if in the same alpha index.
  16106. *
  16107. * @param a The first submesh
  16108. * @param b The second submesh
  16109. * @returns The result of the comparison
  16110. */
  16111. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16112. // Alpha index first
  16113. if (a._alphaIndex > b._alphaIndex) {
  16114. return 1;
  16115. }
  16116. if (a._alphaIndex < b._alphaIndex) {
  16117. return -1;
  16118. }
  16119. // Then distance to camera
  16120. return RenderingGroup.backToFrontSortCompare(a, b);
  16121. };
  16122. /**
  16123. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16124. * are rendered back to front.
  16125. *
  16126. * @param a The first submesh
  16127. * @param b The second submesh
  16128. * @returns The result of the comparison
  16129. */
  16130. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16131. // Then distance to camera
  16132. if (a._distanceToCamera < b._distanceToCamera) {
  16133. return 1;
  16134. }
  16135. if (a._distanceToCamera > b._distanceToCamera) {
  16136. return -1;
  16137. }
  16138. return 0;
  16139. };
  16140. /**
  16141. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16142. * are rendered front to back (prevent overdraw).
  16143. *
  16144. * @param a The first submesh
  16145. * @param b The second submesh
  16146. * @returns The result of the comparison
  16147. */
  16148. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16149. // Then distance to camera
  16150. if (a._distanceToCamera < b._distanceToCamera) {
  16151. return -1;
  16152. }
  16153. if (a._distanceToCamera > b._distanceToCamera) {
  16154. return 1;
  16155. }
  16156. return 0;
  16157. };
  16158. /**
  16159. * Resets the different lists of submeshes to prepare a new frame.
  16160. */
  16161. RenderingGroup.prototype.prepare = function () {
  16162. this._opaqueSubMeshes.reset();
  16163. this._transparentSubMeshes.reset();
  16164. this._alphaTestSubMeshes.reset();
  16165. this._particleSystems.reset();
  16166. this._spriteManagers.reset();
  16167. this._edgesRenderers.reset();
  16168. };
  16169. RenderingGroup.prototype.dispose = function () {
  16170. this._opaqueSubMeshes.dispose();
  16171. this._transparentSubMeshes.dispose();
  16172. this._alphaTestSubMeshes.dispose();
  16173. this._particleSystems.dispose();
  16174. this._spriteManagers.dispose();
  16175. this._edgesRenderers.dispose();
  16176. };
  16177. /**
  16178. * Inserts the submesh in its correct queue depending on its material.
  16179. * @param subMesh The submesh to dispatch
  16180. */
  16181. RenderingGroup.prototype.dispatch = function (subMesh) {
  16182. var material = subMesh.getMaterial();
  16183. var mesh = subMesh.getMesh();
  16184. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16185. this._transparentSubMeshes.push(subMesh);
  16186. }
  16187. else if (material.needAlphaTesting()) {
  16188. this._alphaTestSubMeshes.push(subMesh);
  16189. }
  16190. else {
  16191. this._opaqueSubMeshes.push(subMesh); // Opaque
  16192. }
  16193. if (mesh._edgesRenderer) {
  16194. this._edgesRenderers.push(mesh._edgesRenderer);
  16195. }
  16196. };
  16197. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16198. this._spriteManagers.push(spriteManager);
  16199. };
  16200. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16201. this._particleSystems.push(particleSystem);
  16202. };
  16203. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16204. if (this._particleSystems.length === 0) {
  16205. return;
  16206. }
  16207. // Particles
  16208. var activeCamera = this._scene.activeCamera;
  16209. this._scene._particlesDuration.beginMonitoring();
  16210. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16211. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16212. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16213. continue;
  16214. }
  16215. var emitter = particleSystem.emitter;
  16216. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16217. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16218. }
  16219. }
  16220. this._scene._particlesDuration.endMonitoring(false);
  16221. };
  16222. RenderingGroup.prototype._renderSprites = function () {
  16223. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16224. return;
  16225. }
  16226. // Sprites
  16227. var activeCamera = this._scene.activeCamera;
  16228. this._scene._spritesDuration.beginMonitoring();
  16229. for (var id = 0; id < this._spriteManagers.length; id++) {
  16230. var spriteManager = this._spriteManagers.data[id];
  16231. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16232. spriteManager.render();
  16233. }
  16234. }
  16235. this._scene._spritesDuration.endMonitoring(false);
  16236. };
  16237. return RenderingGroup;
  16238. }());
  16239. BABYLON.RenderingGroup = RenderingGroup;
  16240. })(BABYLON || (BABYLON = {}));
  16241. //# sourceMappingURL=babylon.renderingGroup.js.map
  16242. var BABYLON;
  16243. (function (BABYLON) {
  16244. var ClickInfo = (function () {
  16245. function ClickInfo() {
  16246. this._singleClick = false;
  16247. this._doubleClick = false;
  16248. this._hasSwiped = false;
  16249. this._ignore = false;
  16250. }
  16251. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16252. get: function () {
  16253. return this._singleClick;
  16254. },
  16255. set: function (b) {
  16256. this._singleClick = b;
  16257. },
  16258. enumerable: true,
  16259. configurable: true
  16260. });
  16261. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16262. get: function () {
  16263. return this._doubleClick;
  16264. },
  16265. set: function (b) {
  16266. this._doubleClick = b;
  16267. },
  16268. enumerable: true,
  16269. configurable: true
  16270. });
  16271. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16272. get: function () {
  16273. return this._hasSwiped;
  16274. },
  16275. set: function (b) {
  16276. this._hasSwiped = b;
  16277. },
  16278. enumerable: true,
  16279. configurable: true
  16280. });
  16281. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16282. get: function () {
  16283. return this._ignore;
  16284. },
  16285. set: function (b) {
  16286. this._ignore = b;
  16287. },
  16288. enumerable: true,
  16289. configurable: true
  16290. });
  16291. return ClickInfo;
  16292. }());
  16293. /**
  16294. * This class is used by the onRenderingGroupObservable
  16295. */
  16296. var RenderingGroupInfo = (function () {
  16297. function RenderingGroupInfo() {
  16298. }
  16299. /**
  16300. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16301. * This stage will be fired no matter what
  16302. */
  16303. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16304. /**
  16305. * Called before opaque object are rendered.
  16306. * This stage will be fired only if there's 3D Opaque content to render
  16307. */
  16308. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16309. /**
  16310. * Called after the opaque objects are rendered and before the transparent ones
  16311. * This stage will be fired only if there's 3D transparent content to render
  16312. */
  16313. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16314. /**
  16315. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16316. * This stage will be fired no matter what
  16317. */
  16318. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16319. return RenderingGroupInfo;
  16320. }());
  16321. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16322. /**
  16323. * Represents a scene to be rendered by the engine.
  16324. * @see http://doc.babylonjs.com/page.php?p=21911
  16325. */
  16326. var Scene = (function () {
  16327. /**
  16328. * @constructor
  16329. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16330. */
  16331. function Scene(engine) {
  16332. // Members
  16333. this.autoClear = true;
  16334. this.autoClearDepthAndStencil = true;
  16335. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16336. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16337. this.forceWireframe = false;
  16338. this._forcePointsCloud = false;
  16339. this.forceShowBoundingBoxes = false;
  16340. this.animationsEnabled = true;
  16341. this.constantlyUpdateMeshUnderPointer = false;
  16342. this.hoverCursor = "pointer";
  16343. this.defaultCursor = "";
  16344. // Metadata
  16345. this.metadata = null;
  16346. // Events
  16347. /**
  16348. * An event triggered when the scene is disposed.
  16349. * @type {BABYLON.Observable}
  16350. */
  16351. this.onDisposeObservable = new BABYLON.Observable();
  16352. /**
  16353. * An event triggered before rendering the scene
  16354. * @type {BABYLON.Observable}
  16355. */
  16356. this.onBeforeRenderObservable = new BABYLON.Observable();
  16357. /**
  16358. * An event triggered after rendering the scene
  16359. * @type {BABYLON.Observable}
  16360. */
  16361. this.onAfterRenderObservable = new BABYLON.Observable();
  16362. /**
  16363. * An event triggered when the scene is ready
  16364. * @type {BABYLON.Observable}
  16365. */
  16366. this.onReadyObservable = new BABYLON.Observable();
  16367. /**
  16368. * An event triggered before rendering a camera
  16369. * @type {BABYLON.Observable}
  16370. */
  16371. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16372. /**
  16373. * An event triggered after rendering a camera
  16374. * @type {BABYLON.Observable}
  16375. */
  16376. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16377. /**
  16378. * An event triggered when a camera is created
  16379. * @type {BABYLON.Observable}
  16380. */
  16381. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16382. /**
  16383. * An event triggered when a camera is removed
  16384. * @type {BABYLON.Observable}
  16385. */
  16386. this.onCameraRemovedObservable = new BABYLON.Observable();
  16387. /**
  16388. * An event triggered when a light is created
  16389. * @type {BABYLON.Observable}
  16390. */
  16391. this.onNewLightAddedObservable = new BABYLON.Observable();
  16392. /**
  16393. * An event triggered when a light is removed
  16394. * @type {BABYLON.Observable}
  16395. */
  16396. this.onLightRemovedObservable = new BABYLON.Observable();
  16397. /**
  16398. * An event triggered when a geometry is created
  16399. * @type {BABYLON.Observable}
  16400. */
  16401. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16402. /**
  16403. * An event triggered when a geometry is removed
  16404. * @type {BABYLON.Observable}
  16405. */
  16406. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16407. /**
  16408. * An event triggered when a mesh is created
  16409. * @type {BABYLON.Observable}
  16410. */
  16411. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16412. /**
  16413. * An event triggered when a mesh is removed
  16414. * @type {BABYLON.Observable}
  16415. */
  16416. this.onMeshRemovedObservable = new BABYLON.Observable();
  16417. /**
  16418. * An event triggered before calculating deterministic simulation step
  16419. * @type {BABYLON.Observable}
  16420. */
  16421. this.onBeforeStepObservable = new BABYLON.Observable();
  16422. /**
  16423. * An event triggered after calculating deterministic simulation step
  16424. * @type {BABYLON.Observable}
  16425. */
  16426. this.onAfterStepObservable = new BABYLON.Observable();
  16427. /**
  16428. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16429. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16430. * 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)
  16431. */
  16432. this.onRenderingGroupObservable = new BABYLON.Observable();
  16433. // Animations
  16434. this.animations = [];
  16435. /**
  16436. * 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).
  16437. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  16438. */
  16439. this.onPrePointerObservable = new BABYLON.Observable();
  16440. /**
  16441. * Observable event triggered each time an input event is received from the rendering canvas
  16442. */
  16443. this.onPointerObservable = new BABYLON.Observable();
  16444. this._meshPickProceed = false;
  16445. this._previousHasSwiped = false;
  16446. this._currentPickResult = null;
  16447. this._previousPickResult = null;
  16448. this._isButtonPressed = false;
  16449. this._doubleClickOccured = false;
  16450. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16451. this.cameraToUseForPointers = null;
  16452. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16453. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16454. this._startingPointerTime = 0;
  16455. this._previousStartingPointerTime = 0;
  16456. // Deterministic lockstep
  16457. this._timeAccumulator = 0;
  16458. this._currentStepId = 0;
  16459. this._currentInternalStep = 0;
  16460. // Keyboard
  16461. /**
  16462. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  16463. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  16464. */
  16465. this.onPreKeyboardObservable = new BABYLON.Observable();
  16466. /**
  16467. * Observable event triggered each time an keyboard event is received from the hosting window
  16468. */
  16469. this.onKeyboardObservable = new BABYLON.Observable();
  16470. // Coordinate system
  16471. /**
  16472. * use right-handed coordinate system on this scene.
  16473. * @type {boolean}
  16474. */
  16475. this._useRightHandedSystem = false;
  16476. // Fog
  16477. this._fogEnabled = true;
  16478. this._fogMode = Scene.FOGMODE_NONE;
  16479. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16480. this.fogDensity = 0.1;
  16481. this.fogStart = 0;
  16482. this.fogEnd = 1000.0;
  16483. // Lights
  16484. /**
  16485. * is shadow enabled on this scene.
  16486. * @type {boolean}
  16487. */
  16488. this._shadowsEnabled = true;
  16489. /**
  16490. * is light enabled on this scene.
  16491. * @type {boolean}
  16492. */
  16493. this._lightsEnabled = true;
  16494. /**
  16495. * All of the lights added to this scene.
  16496. * @see BABYLON.Light
  16497. * @type {BABYLON.Light[]}
  16498. */
  16499. this.lights = new Array();
  16500. // Cameras
  16501. /** All of the cameras added to this scene. */
  16502. this.cameras = new Array();
  16503. /** All of the active cameras added to this scene. */
  16504. this.activeCameras = new Array();
  16505. // Meshes
  16506. /**
  16507. * All of the (abstract) meshes added to this scene.
  16508. * @see BABYLON.AbstractMesh
  16509. * @type {BABYLON.AbstractMesh[]}
  16510. */
  16511. this.meshes = new Array();
  16512. // Geometries
  16513. this._geometries = new Array();
  16514. this.materials = new Array();
  16515. this.multiMaterials = new Array();
  16516. // Textures
  16517. this._texturesEnabled = true;
  16518. this.textures = new Array();
  16519. // Particles
  16520. this.particlesEnabled = true;
  16521. this.particleSystems = new Array();
  16522. // Sprites
  16523. this.spritesEnabled = true;
  16524. this.spriteManagers = new Array();
  16525. // Layers
  16526. this.layers = new Array();
  16527. this.highlightLayers = new Array();
  16528. // Skeletons
  16529. this._skeletonsEnabled = true;
  16530. this.skeletons = new Array();
  16531. // Morph targets
  16532. this.morphTargetManagers = new Array();
  16533. // Lens flares
  16534. this.lensFlaresEnabled = true;
  16535. this.lensFlareSystems = new Array();
  16536. // Collisions
  16537. this.collisionsEnabled = true;
  16538. /** Defines the gravity applied to this scene */
  16539. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16540. // Postprocesses
  16541. this.postProcesses = new Array();
  16542. this.postProcessesEnabled = true;
  16543. // Customs render targets
  16544. this.renderTargetsEnabled = true;
  16545. this.dumpNextRenderTargets = false;
  16546. this.customRenderTargets = new Array();
  16547. // Imported meshes
  16548. this.importedMeshesFiles = new Array();
  16549. // Probes
  16550. this.probesEnabled = true;
  16551. this.reflectionProbes = new Array();
  16552. this._actionManagers = new Array();
  16553. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16554. // Procedural textures
  16555. this.proceduralTexturesEnabled = true;
  16556. this._proceduralTextures = new Array();
  16557. this.soundTracks = new Array();
  16558. this._audioEnabled = true;
  16559. this._headphone = false;
  16560. // Performance counters
  16561. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16562. this._totalLightsCounter = new BABYLON.PerfCounter();
  16563. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16564. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16565. this._totalVertices = new BABYLON.PerfCounter();
  16566. this._activeIndices = new BABYLON.PerfCounter();
  16567. this._activeParticles = new BABYLON.PerfCounter();
  16568. this._lastFrameDuration = new BABYLON.PerfCounter();
  16569. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16570. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16571. this._particlesDuration = new BABYLON.PerfCounter();
  16572. this._renderDuration = new BABYLON.PerfCounter();
  16573. this._spritesDuration = new BABYLON.PerfCounter();
  16574. this._activeBones = new BABYLON.PerfCounter();
  16575. this._animationTime = 0;
  16576. this.animationTimeScale = 1;
  16577. this._renderId = 0;
  16578. this._executeWhenReadyTimeoutId = -1;
  16579. this._intermediateRendering = false;
  16580. this._viewUpdateFlag = -1;
  16581. this._projectionUpdateFlag = -1;
  16582. this._toBeDisposed = new BABYLON.SmartArray(256);
  16583. this._pendingData = []; //ANY
  16584. this._activeMeshes = new BABYLON.SmartArray(256);
  16585. this._processedMaterials = new BABYLON.SmartArray(256);
  16586. this._renderTargets = new BABYLON.SmartArray(256);
  16587. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16588. this._activeSkeletons = new BABYLON.SmartArray(32);
  16589. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16590. this._activeAnimatables = new Array();
  16591. this._transformMatrix = BABYLON.Matrix.Zero();
  16592. this.requireLightSorting = false;
  16593. this._uniqueIdCounter = 0;
  16594. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16595. this._engine.scenes.push(this);
  16596. this._uid = null;
  16597. this._renderingManager = new BABYLON.RenderingManager(this);
  16598. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16599. if (BABYLON.OutlineRenderer) {
  16600. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16601. }
  16602. this.attachControl();
  16603. if (BABYLON.SoundTrack) {
  16604. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16605. }
  16606. //simplification queue
  16607. if (BABYLON.SimplificationQueue) {
  16608. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16609. }
  16610. //collision coordinator initialization. For now legacy per default.
  16611. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16612. // Uniform Buffer
  16613. this._createUbo();
  16614. // Default Image processing definition.
  16615. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16616. }
  16617. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16618. /** The fog is deactivated */
  16619. get: function () {
  16620. return Scene._FOGMODE_NONE;
  16621. },
  16622. enumerable: true,
  16623. configurable: true
  16624. });
  16625. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16626. /** The fog density is following an exponential function */
  16627. get: function () {
  16628. return Scene._FOGMODE_EXP;
  16629. },
  16630. enumerable: true,
  16631. configurable: true
  16632. });
  16633. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16634. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16635. get: function () {
  16636. return Scene._FOGMODE_EXP2;
  16637. },
  16638. enumerable: true,
  16639. configurable: true
  16640. });
  16641. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16642. /** The fog density is following a linear function. */
  16643. get: function () {
  16644. return Scene._FOGMODE_LINEAR;
  16645. },
  16646. enumerable: true,
  16647. configurable: true
  16648. });
  16649. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16650. /**
  16651. * Texture used in all pbr material as the reflection texture.
  16652. * As in the majority of the scene they are the same (exception for multi room and so on),
  16653. * this is easier to reference from here than from all the materials.
  16654. */
  16655. get: function () {
  16656. return this._environmentTexture;
  16657. },
  16658. /**
  16659. * Texture used in all pbr material as the reflection texture.
  16660. * As in the majority of the scene they are the same (exception for multi room and so on),
  16661. * this is easier to set here than in all the materials.
  16662. */
  16663. set: function (value) {
  16664. this._environmentTexture = value;
  16665. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16666. },
  16667. enumerable: true,
  16668. configurable: true
  16669. });
  16670. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16671. /**
  16672. * Default image processing configuration used either in the rendering
  16673. * Forward main pass or through the imageProcessingPostProcess if present.
  16674. * As in the majority of the scene they are the same (exception for multi camera),
  16675. * this is easier to reference from here than from all the materials and post process.
  16676. *
  16677. * No setter as we it is a shared configuration, you can set the values instead.
  16678. */
  16679. get: function () {
  16680. return this._imageProcessingConfiguration;
  16681. },
  16682. enumerable: true,
  16683. configurable: true
  16684. });
  16685. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16686. get: function () {
  16687. return this._forcePointsCloud;
  16688. },
  16689. set: function (value) {
  16690. if (this._forcePointsCloud === value) {
  16691. return;
  16692. }
  16693. this._forcePointsCloud = value;
  16694. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16695. },
  16696. enumerable: true,
  16697. configurable: true
  16698. });
  16699. Object.defineProperty(Scene.prototype, "onDispose", {
  16700. /** A function to be executed when this scene is disposed. */
  16701. set: function (callback) {
  16702. if (this._onDisposeObserver) {
  16703. this.onDisposeObservable.remove(this._onDisposeObserver);
  16704. }
  16705. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16706. },
  16707. enumerable: true,
  16708. configurable: true
  16709. });
  16710. Object.defineProperty(Scene.prototype, "beforeRender", {
  16711. /** A function to be executed before rendering this scene */
  16712. set: function (callback) {
  16713. if (this._onBeforeRenderObserver) {
  16714. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16715. }
  16716. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16717. },
  16718. enumerable: true,
  16719. configurable: true
  16720. });
  16721. Object.defineProperty(Scene.prototype, "afterRender", {
  16722. /** A function to be executed after rendering this scene */
  16723. set: function (callback) {
  16724. if (this._onAfterRenderObserver) {
  16725. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16726. }
  16727. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16728. },
  16729. enumerable: true,
  16730. configurable: true
  16731. });
  16732. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16733. set: function (callback) {
  16734. if (this._onBeforeCameraRenderObserver) {
  16735. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16736. }
  16737. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16738. },
  16739. enumerable: true,
  16740. configurable: true
  16741. });
  16742. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16743. set: function (callback) {
  16744. if (this._onAfterCameraRenderObserver) {
  16745. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16746. }
  16747. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16748. },
  16749. enumerable: true,
  16750. configurable: true
  16751. });
  16752. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16753. get: function () {
  16754. if (!this._gamepadManager) {
  16755. this._gamepadManager = new BABYLON.GamepadManager();
  16756. }
  16757. return this._gamepadManager;
  16758. },
  16759. enumerable: true,
  16760. configurable: true
  16761. });
  16762. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16763. get: function () {
  16764. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16765. },
  16766. enumerable: true,
  16767. configurable: true
  16768. });
  16769. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16770. get: function () {
  16771. return this._useRightHandedSystem;
  16772. },
  16773. set: function (value) {
  16774. if (this._useRightHandedSystem === value) {
  16775. return;
  16776. }
  16777. this._useRightHandedSystem = value;
  16778. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16779. },
  16780. enumerable: true,
  16781. configurable: true
  16782. });
  16783. Scene.prototype.setStepId = function (newStepId) {
  16784. this._currentStepId = newStepId;
  16785. };
  16786. ;
  16787. Scene.prototype.getStepId = function () {
  16788. return this._currentStepId;
  16789. };
  16790. ;
  16791. Scene.prototype.getInternalStep = function () {
  16792. return this._currentInternalStep;
  16793. };
  16794. ;
  16795. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16796. get: function () {
  16797. return this._fogEnabled;
  16798. },
  16799. /**
  16800. * is fog enabled on this scene.
  16801. */
  16802. set: function (value) {
  16803. if (this._fogEnabled === value) {
  16804. return;
  16805. }
  16806. this._fogEnabled = value;
  16807. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16808. },
  16809. enumerable: true,
  16810. configurable: true
  16811. });
  16812. Object.defineProperty(Scene.prototype, "fogMode", {
  16813. get: function () {
  16814. return this._fogMode;
  16815. },
  16816. set: function (value) {
  16817. if (this._fogMode === value) {
  16818. return;
  16819. }
  16820. this._fogMode = value;
  16821. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16822. },
  16823. enumerable: true,
  16824. configurable: true
  16825. });
  16826. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16827. get: function () {
  16828. return this._shadowsEnabled;
  16829. },
  16830. set: function (value) {
  16831. if (this._shadowsEnabled === value) {
  16832. return;
  16833. }
  16834. this._shadowsEnabled = value;
  16835. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16836. },
  16837. enumerable: true,
  16838. configurable: true
  16839. });
  16840. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16841. get: function () {
  16842. return this._lightsEnabled;
  16843. },
  16844. set: function (value) {
  16845. if (this._lightsEnabled === value) {
  16846. return;
  16847. }
  16848. this._lightsEnabled = value;
  16849. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16850. },
  16851. enumerable: true,
  16852. configurable: true
  16853. });
  16854. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16855. /** The default material used on meshes when no material is affected */
  16856. get: function () {
  16857. if (!this._defaultMaterial) {
  16858. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16859. }
  16860. return this._defaultMaterial;
  16861. },
  16862. /** The default material used on meshes when no material is affected */
  16863. set: function (value) {
  16864. this._defaultMaterial = value;
  16865. },
  16866. enumerable: true,
  16867. configurable: true
  16868. });
  16869. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16870. get: function () {
  16871. return this._texturesEnabled;
  16872. },
  16873. set: function (value) {
  16874. if (this._texturesEnabled === value) {
  16875. return;
  16876. }
  16877. this._texturesEnabled = value;
  16878. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16879. },
  16880. enumerable: true,
  16881. configurable: true
  16882. });
  16883. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16884. get: function () {
  16885. return this._skeletonsEnabled;
  16886. },
  16887. set: function (value) {
  16888. if (this._skeletonsEnabled === value) {
  16889. return;
  16890. }
  16891. this._skeletonsEnabled = value;
  16892. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16893. },
  16894. enumerable: true,
  16895. configurable: true
  16896. });
  16897. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16898. get: function () {
  16899. if (!this._postProcessRenderPipelineManager) {
  16900. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16901. }
  16902. return this._postProcessRenderPipelineManager;
  16903. },
  16904. enumerable: true,
  16905. configurable: true
  16906. });
  16907. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16908. get: function () {
  16909. return this._frustumPlanes;
  16910. },
  16911. enumerable: true,
  16912. configurable: true
  16913. });
  16914. Object.defineProperty(Scene.prototype, "debugLayer", {
  16915. // Properties
  16916. get: function () {
  16917. if (!this._debugLayer) {
  16918. this._debugLayer = new BABYLON.DebugLayer(this);
  16919. }
  16920. return this._debugLayer;
  16921. },
  16922. enumerable: true,
  16923. configurable: true
  16924. });
  16925. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16926. get: function () {
  16927. return this._workerCollisions;
  16928. },
  16929. set: function (enabled) {
  16930. if (!BABYLON.CollisionCoordinatorLegacy) {
  16931. return;
  16932. }
  16933. enabled = (enabled && !!Worker);
  16934. this._workerCollisions = enabled;
  16935. if (this.collisionCoordinator) {
  16936. this.collisionCoordinator.destroy();
  16937. }
  16938. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16939. this.collisionCoordinator.init(this);
  16940. },
  16941. enumerable: true,
  16942. configurable: true
  16943. });
  16944. Object.defineProperty(Scene.prototype, "selectionOctree", {
  16945. get: function () {
  16946. return this._selectionOctree;
  16947. },
  16948. enumerable: true,
  16949. configurable: true
  16950. });
  16951. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16952. /**
  16953. * The mesh that is currently under the pointer.
  16954. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16955. */
  16956. get: function () {
  16957. return this._pointerOverMesh;
  16958. },
  16959. enumerable: true,
  16960. configurable: true
  16961. });
  16962. Object.defineProperty(Scene.prototype, "pointerX", {
  16963. /**
  16964. * Current on-screen X position of the pointer
  16965. * @return {number} X position of the pointer
  16966. */
  16967. get: function () {
  16968. return this._pointerX;
  16969. },
  16970. enumerable: true,
  16971. configurable: true
  16972. });
  16973. Object.defineProperty(Scene.prototype, "pointerY", {
  16974. /**
  16975. * Current on-screen Y position of the pointer
  16976. * @return {number} Y position of the pointer
  16977. */
  16978. get: function () {
  16979. return this._pointerY;
  16980. },
  16981. enumerable: true,
  16982. configurable: true
  16983. });
  16984. Scene.prototype.getCachedMaterial = function () {
  16985. return this._cachedMaterial;
  16986. };
  16987. Scene.prototype.getCachedEffect = function () {
  16988. return this._cachedEffect;
  16989. };
  16990. Scene.prototype.getCachedVisibility = function () {
  16991. return this._cachedVisibility;
  16992. };
  16993. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  16994. if (visibility === void 0) { visibility = 1; }
  16995. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16996. };
  16997. Scene.prototype.getBoundingBoxRenderer = function () {
  16998. if (!this._boundingBoxRenderer) {
  16999. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17000. }
  17001. return this._boundingBoxRenderer;
  17002. };
  17003. Scene.prototype.getOutlineRenderer = function () {
  17004. return this._outlineRenderer;
  17005. };
  17006. Scene.prototype.getEngine = function () {
  17007. return this._engine;
  17008. };
  17009. Scene.prototype.getTotalVertices = function () {
  17010. return this._totalVertices.current;
  17011. };
  17012. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17013. get: function () {
  17014. return this._totalVertices;
  17015. },
  17016. enumerable: true,
  17017. configurable: true
  17018. });
  17019. Scene.prototype.getActiveIndices = function () {
  17020. return this._activeIndices.current;
  17021. };
  17022. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17023. get: function () {
  17024. return this._activeIndices;
  17025. },
  17026. enumerable: true,
  17027. configurable: true
  17028. });
  17029. Scene.prototype.getActiveParticles = function () {
  17030. return this._activeParticles.current;
  17031. };
  17032. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17033. get: function () {
  17034. return this._activeParticles;
  17035. },
  17036. enumerable: true,
  17037. configurable: true
  17038. });
  17039. Scene.prototype.getActiveBones = function () {
  17040. return this._activeBones.current;
  17041. };
  17042. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17043. get: function () {
  17044. return this._activeBones;
  17045. },
  17046. enumerable: true,
  17047. configurable: true
  17048. });
  17049. // Stats
  17050. Scene.prototype.getLastFrameDuration = function () {
  17051. return this._lastFrameDuration.current;
  17052. };
  17053. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17054. get: function () {
  17055. return this._lastFrameDuration;
  17056. },
  17057. enumerable: true,
  17058. configurable: true
  17059. });
  17060. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17061. return this._evaluateActiveMeshesDuration.current;
  17062. };
  17063. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17064. get: function () {
  17065. return this._evaluateActiveMeshesDuration;
  17066. },
  17067. enumerable: true,
  17068. configurable: true
  17069. });
  17070. Scene.prototype.getActiveMeshes = function () {
  17071. return this._activeMeshes;
  17072. };
  17073. Scene.prototype.getRenderTargetsDuration = function () {
  17074. return this._renderTargetsDuration.current;
  17075. };
  17076. Scene.prototype.getRenderDuration = function () {
  17077. return this._renderDuration.current;
  17078. };
  17079. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17080. get: function () {
  17081. return this._renderDuration;
  17082. },
  17083. enumerable: true,
  17084. configurable: true
  17085. });
  17086. Scene.prototype.getParticlesDuration = function () {
  17087. return this._particlesDuration.current;
  17088. };
  17089. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17090. get: function () {
  17091. return this._particlesDuration;
  17092. },
  17093. enumerable: true,
  17094. configurable: true
  17095. });
  17096. Scene.prototype.getSpritesDuration = function () {
  17097. return this._spritesDuration.current;
  17098. };
  17099. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17100. get: function () {
  17101. return this._spritesDuration;
  17102. },
  17103. enumerable: true,
  17104. configurable: true
  17105. });
  17106. Scene.prototype.getAnimationRatio = function () {
  17107. return this._animationRatio;
  17108. };
  17109. Scene.prototype.getRenderId = function () {
  17110. return this._renderId;
  17111. };
  17112. Scene.prototype.incrementRenderId = function () {
  17113. this._renderId++;
  17114. };
  17115. Scene.prototype._updatePointerPosition = function (evt) {
  17116. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17117. this._pointerX = evt.clientX - canvasRect.left;
  17118. this._pointerY = evt.clientY - canvasRect.top;
  17119. this._unTranslatedPointerX = this._pointerX;
  17120. this._unTranslatedPointerY = this._pointerY;
  17121. };
  17122. Scene.prototype._createUbo = function () {
  17123. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17124. this._sceneUbo.addUniform("viewProjection", 16);
  17125. this._sceneUbo.addUniform("view", 16);
  17126. };
  17127. // Pointers handling
  17128. /**
  17129. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17130. * @param attachUp defines if you want to attach events to pointerup
  17131. * @param attachDown defines if you want to attach events to pointerdown
  17132. * @param attachMove defines if you want to attach events to pointermove
  17133. */
  17134. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17135. var _this = this;
  17136. if (attachUp === void 0) { attachUp = true; }
  17137. if (attachDown === void 0) { attachDown = true; }
  17138. if (attachMove === void 0) { attachMove = true; }
  17139. this._initActionManager = function (act, clickInfo) {
  17140. if (!_this._meshPickProceed) {
  17141. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17142. _this._currentPickResult = pickResult;
  17143. if (pickResult) {
  17144. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17145. }
  17146. _this._meshPickProceed = true;
  17147. }
  17148. return act;
  17149. };
  17150. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17151. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17152. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17153. btn !== _this._previousButtonPressed) {
  17154. _this._doubleClickOccured = false;
  17155. clickInfo.singleClick = true;
  17156. clickInfo.ignore = false;
  17157. cb(clickInfo, _this._currentPickResult);
  17158. }
  17159. };
  17160. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17161. var clickInfo = new ClickInfo();
  17162. _this._currentPickResult = null;
  17163. var act;
  17164. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  17165. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  17166. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17167. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17168. act = _this._initActionManager(act, clickInfo);
  17169. if (act)
  17170. checkPicking = act.hasPickTriggers;
  17171. }
  17172. if (checkPicking) {
  17173. var btn = evt.button;
  17174. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17175. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17176. if (!clickInfo.hasSwiped) {
  17177. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17178. if (!checkSingleClickImmediately) {
  17179. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  17180. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17181. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17182. act = _this._initActionManager(act, clickInfo);
  17183. if (act)
  17184. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17185. }
  17186. }
  17187. if (checkSingleClickImmediately) {
  17188. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17189. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17190. btn !== _this._previousButtonPressed) {
  17191. clickInfo.singleClick = true;
  17192. cb(clickInfo, _this._currentPickResult);
  17193. }
  17194. }
  17195. else {
  17196. // wait that no double click has been raised during the double click delay
  17197. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17198. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17199. }
  17200. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  17201. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17202. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17203. act = _this._initActionManager(act, clickInfo);
  17204. if (act)
  17205. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17206. }
  17207. if (checkDoubleClick) {
  17208. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17209. if (btn === _this._previousButtonPressed &&
  17210. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17211. !_this._doubleClickOccured) {
  17212. // pointer has not moved for 2 clicks, it's a double click
  17213. if (!clickInfo.hasSwiped &&
  17214. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17215. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17216. _this._previousStartingPointerTime = 0;
  17217. _this._doubleClickOccured = true;
  17218. clickInfo.doubleClick = true;
  17219. clickInfo.ignore = false;
  17220. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17221. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17222. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17223. cb(clickInfo, _this._currentPickResult);
  17224. }
  17225. else {
  17226. _this._doubleClickOccured = false;
  17227. _this._previousStartingPointerTime = _this._startingPointerTime;
  17228. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17229. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17230. _this._previousButtonPressed = btn;
  17231. _this._previousHasSwiped = clickInfo.hasSwiped;
  17232. if (Scene.ExclusiveDoubleClickMode) {
  17233. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17234. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17235. }
  17236. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17237. cb(clickInfo, _this._previousPickResult);
  17238. }
  17239. else {
  17240. cb(clickInfo, _this._currentPickResult);
  17241. }
  17242. }
  17243. }
  17244. else {
  17245. _this._doubleClickOccured = false;
  17246. _this._previousStartingPointerTime = _this._startingPointerTime;
  17247. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17248. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17249. _this._previousButtonPressed = btn;
  17250. _this._previousHasSwiped = clickInfo.hasSwiped;
  17251. }
  17252. }
  17253. }
  17254. }
  17255. clickInfo.ignore = true;
  17256. cb(clickInfo, _this._currentPickResult);
  17257. };
  17258. var spritePredicate = function (sprite) {
  17259. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17260. };
  17261. this._onPointerMove = function (evt) {
  17262. _this._updatePointerPosition(evt);
  17263. // PreObservable support
  17264. if (_this.onPrePointerObservable.hasObservers()) {
  17265. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17266. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17267. _this.onPrePointerObservable.notifyObservers(pi, type);
  17268. if (pi.skipOnPointerObservable) {
  17269. return;
  17270. }
  17271. }
  17272. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17273. return;
  17274. }
  17275. var canvas = _this._engine.getRenderingCanvas();
  17276. if (!_this.pointerMovePredicate) {
  17277. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17278. }
  17279. // Meshes
  17280. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17281. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17282. _this.setPointerOverSprite(null);
  17283. _this.setPointerOverMesh(pickResult.pickedMesh);
  17284. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17285. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17286. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17287. }
  17288. else {
  17289. canvas.style.cursor = _this.hoverCursor;
  17290. }
  17291. }
  17292. else {
  17293. canvas.style.cursor = _this.defaultCursor;
  17294. }
  17295. }
  17296. else {
  17297. _this.setPointerOverMesh(null);
  17298. // Sprites
  17299. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17300. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17301. _this.setPointerOverSprite(pickResult.pickedSprite);
  17302. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17303. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17304. }
  17305. else {
  17306. canvas.style.cursor = _this.hoverCursor;
  17307. }
  17308. }
  17309. else {
  17310. _this.setPointerOverSprite(null);
  17311. // Restore pointer
  17312. canvas.style.cursor = _this.defaultCursor;
  17313. }
  17314. }
  17315. if (_this.onPointerMove) {
  17316. _this.onPointerMove(evt, pickResult);
  17317. }
  17318. if (_this.onPointerObservable.hasObservers()) {
  17319. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17320. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17321. _this.onPointerObservable.notifyObservers(pi, type);
  17322. }
  17323. };
  17324. this._onPointerDown = function (evt) {
  17325. _this._isButtonPressed = true;
  17326. _this._pickedDownMesh = null;
  17327. _this._meshPickProceed = false;
  17328. _this._updatePointerPosition(evt);
  17329. // PreObservable support
  17330. if (_this.onPrePointerObservable.hasObservers()) {
  17331. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17332. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17333. _this.onPrePointerObservable.notifyObservers(pi, type);
  17334. if (pi.skipOnPointerObservable) {
  17335. return;
  17336. }
  17337. }
  17338. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17339. return;
  17340. }
  17341. _this._startingPointerPosition.x = _this._pointerX;
  17342. _this._startingPointerPosition.y = _this._pointerY;
  17343. _this._startingPointerTime = new Date().getTime();
  17344. if (!_this.pointerDownPredicate) {
  17345. _this.pointerDownPredicate = function (mesh) {
  17346. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17347. };
  17348. }
  17349. // Meshes
  17350. _this._pickedDownMesh = null;
  17351. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17352. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17353. _this._pickedDownMesh = pickResult.pickedMesh;
  17354. var actionManager = pickResult.pickedMesh.actionManager;
  17355. if (actionManager) {
  17356. if (actionManager.hasPickTriggers) {
  17357. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17358. switch (evt.button) {
  17359. case 0:
  17360. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17361. break;
  17362. case 1:
  17363. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17364. break;
  17365. case 2:
  17366. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17367. break;
  17368. }
  17369. }
  17370. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17371. window.setTimeout((function () {
  17372. var _this = this;
  17373. 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);
  17374. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17375. if (this._isButtonPressed &&
  17376. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17377. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17378. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17379. this._startingPointerTime = 0;
  17380. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17381. }
  17382. }
  17383. }).bind(_this), Scene.LongPressDelay);
  17384. }
  17385. }
  17386. }
  17387. if (_this.onPointerDown) {
  17388. _this.onPointerDown(evt, pickResult);
  17389. }
  17390. if (_this.onPointerObservable.hasObservers()) {
  17391. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17392. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17393. _this.onPointerObservable.notifyObservers(pi, type);
  17394. }
  17395. // Sprites
  17396. _this._pickedDownSprite = null;
  17397. if (_this.spriteManagers.length > 0) {
  17398. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17399. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17400. if (pickResult.pickedSprite.actionManager) {
  17401. _this._pickedDownSprite = pickResult.pickedSprite;
  17402. switch (evt.button) {
  17403. case 0:
  17404. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17405. break;
  17406. case 1:
  17407. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17408. break;
  17409. case 2:
  17410. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17411. break;
  17412. }
  17413. if (pickResult.pickedSprite.actionManager) {
  17414. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17415. }
  17416. }
  17417. }
  17418. }
  17419. };
  17420. this._onPointerUp = function (evt) {
  17421. _this._isButtonPressed = false;
  17422. _this._pickedUpMesh = null;
  17423. _this._meshPickProceed = false;
  17424. _this._updatePointerPosition(evt);
  17425. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17426. // PreObservable support
  17427. if (this.onPrePointerObservable.hasObservers()) {
  17428. if (!clickInfo.ignore) {
  17429. if (!clickInfo.hasSwiped) {
  17430. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17431. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17432. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17433. this.onPrePointerObservable.notifyObservers(pi, type);
  17434. if (pi.skipOnPointerObservable) {
  17435. return;
  17436. }
  17437. }
  17438. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17439. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17440. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17441. this.onPrePointerObservable.notifyObservers(pi, type);
  17442. if (pi.skipOnPointerObservable) {
  17443. return;
  17444. }
  17445. }
  17446. }
  17447. }
  17448. else {
  17449. var type = BABYLON.PointerEventTypes.POINTERUP;
  17450. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17451. this.onPrePointerObservable.notifyObservers(pi, type);
  17452. if (pi.skipOnPointerObservable) {
  17453. return;
  17454. }
  17455. }
  17456. }
  17457. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17458. return;
  17459. }
  17460. if (!this.pointerUpPredicate) {
  17461. this.pointerUpPredicate = function (mesh) {
  17462. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17463. };
  17464. }
  17465. // Meshes
  17466. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17467. this._initActionManager(null, clickInfo);
  17468. }
  17469. if (!pickResult) {
  17470. pickResult = this._currentPickResult;
  17471. }
  17472. if (pickResult && pickResult && pickResult.pickedMesh) {
  17473. this._pickedUpMesh = pickResult.pickedMesh;
  17474. if (this._pickedDownMesh === this._pickedUpMesh) {
  17475. if (this.onPointerPick) {
  17476. this.onPointerPick(evt, pickResult);
  17477. }
  17478. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17479. var type = BABYLON.PointerEventTypes.POINTERPICK;
  17480. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17481. this.onPointerObservable.notifyObservers(pi, type);
  17482. }
  17483. }
  17484. if (pickResult.pickedMesh.actionManager) {
  17485. if (clickInfo.ignore) {
  17486. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17487. }
  17488. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17489. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17490. }
  17491. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17492. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17493. }
  17494. }
  17495. }
  17496. if (this._pickedDownMesh &&
  17497. this._pickedDownMesh.actionManager &&
  17498. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17499. this._pickedDownMesh !== this._pickedUpMesh) {
  17500. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17501. }
  17502. if (this.onPointerUp) {
  17503. this.onPointerUp(evt, pickResult);
  17504. }
  17505. if (this.onPointerObservable.hasObservers()) {
  17506. if (!clickInfo.ignore) {
  17507. if (!clickInfo.hasSwiped) {
  17508. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17509. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17510. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17511. this.onPointerObservable.notifyObservers(pi, type);
  17512. }
  17513. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17514. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17515. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17516. this.onPointerObservable.notifyObservers(pi, type);
  17517. }
  17518. }
  17519. }
  17520. else {
  17521. var type = BABYLON.PointerEventTypes.POINTERUP;
  17522. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17523. this.onPointerObservable.notifyObservers(pi, type);
  17524. }
  17525. }
  17526. // Sprites
  17527. if (this.spriteManagers.length > 0) {
  17528. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  17529. if (pickResult.hit && pickResult.pickedSprite) {
  17530. if (pickResult.pickedSprite.actionManager) {
  17531. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17532. if (pickResult.pickedSprite.actionManager) {
  17533. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17534. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17535. }
  17536. }
  17537. }
  17538. }
  17539. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17540. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17541. }
  17542. }
  17543. this._previousPickResult = this._currentPickResult;
  17544. }).bind(_this));
  17545. };
  17546. this._onKeyDown = function (evt) {
  17547. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  17548. if (_this.onPreKeyboardObservable.hasObservers()) {
  17549. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17550. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17551. if (pi.skipOnPointerObservable) {
  17552. return;
  17553. }
  17554. }
  17555. if (_this.onKeyboardObservable.hasObservers()) {
  17556. var pi = new BABYLON.KeyboardInfo(type, evt);
  17557. _this.onKeyboardObservable.notifyObservers(pi, type);
  17558. }
  17559. if (_this.actionManager) {
  17560. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17561. }
  17562. };
  17563. this._onKeyUp = function (evt) {
  17564. var type = BABYLON.KeyboardEventTypes.KEYUP;
  17565. if (_this.onPreKeyboardObservable.hasObservers()) {
  17566. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17567. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17568. if (pi.skipOnPointerObservable) {
  17569. return;
  17570. }
  17571. }
  17572. if (_this.onKeyboardObservable.hasObservers()) {
  17573. var pi = new BABYLON.KeyboardInfo(type, evt);
  17574. _this.onKeyboardObservable.notifyObservers(pi, type);
  17575. }
  17576. if (_this.actionManager) {
  17577. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17578. }
  17579. };
  17580. var engine = this.getEngine();
  17581. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  17582. canvas.addEventListener("keydown", _this._onKeyDown, false);
  17583. canvas.addEventListener("keyup", _this._onKeyUp, false);
  17584. });
  17585. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  17586. canvas.removeEventListener("keydown", _this._onKeyDown);
  17587. canvas.removeEventListener("keyup", _this._onKeyUp);
  17588. });
  17589. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17590. var canvas = this._engine.getRenderingCanvas();
  17591. if (attachMove) {
  17592. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17593. // Wheel
  17594. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17595. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17596. }
  17597. if (attachDown) {
  17598. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17599. }
  17600. if (attachUp) {
  17601. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17602. }
  17603. canvas.tabIndex = 1;
  17604. };
  17605. Scene.prototype.detachControl = function () {
  17606. var engine = this.getEngine();
  17607. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17608. var canvas = engine.getRenderingCanvas();
  17609. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17610. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17611. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17612. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  17613. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  17614. // Wheel
  17615. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17616. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17617. // Keyboard
  17618. canvas.removeEventListener("keydown", this._onKeyDown);
  17619. canvas.removeEventListener("keyup", this._onKeyUp);
  17620. // Observables
  17621. this.onKeyboardObservable.clear();
  17622. this.onPreKeyboardObservable.clear();
  17623. this.onPointerObservable.clear();
  17624. this.onPrePointerObservable.clear();
  17625. };
  17626. // Ready
  17627. Scene.prototype.isReady = function () {
  17628. if (this._pendingData.length > 0) {
  17629. return false;
  17630. }
  17631. var index;
  17632. // Geometries
  17633. for (index = 0; index < this._geometries.length; index++) {
  17634. var geometry = this._geometries[index];
  17635. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17636. return false;
  17637. }
  17638. }
  17639. // Meshes
  17640. for (index = 0; index < this.meshes.length; index++) {
  17641. var mesh = this.meshes[index];
  17642. if (!mesh.isEnabled()) {
  17643. continue;
  17644. }
  17645. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17646. continue;
  17647. }
  17648. if (!mesh.isReady()) {
  17649. return false;
  17650. }
  17651. var mat = mesh.material;
  17652. if (mat) {
  17653. if (!mat.isReady(mesh)) {
  17654. return false;
  17655. }
  17656. }
  17657. }
  17658. return true;
  17659. };
  17660. Scene.prototype.resetCachedMaterial = function () {
  17661. this._cachedMaterial = null;
  17662. this._cachedEffect = null;
  17663. this._cachedVisibility = null;
  17664. };
  17665. Scene.prototype.registerBeforeRender = function (func) {
  17666. this.onBeforeRenderObservable.add(func);
  17667. };
  17668. Scene.prototype.unregisterBeforeRender = function (func) {
  17669. this.onBeforeRenderObservable.removeCallback(func);
  17670. };
  17671. Scene.prototype.registerAfterRender = function (func) {
  17672. this.onAfterRenderObservable.add(func);
  17673. };
  17674. Scene.prototype.unregisterAfterRender = function (func) {
  17675. this.onAfterRenderObservable.removeCallback(func);
  17676. };
  17677. Scene.prototype._addPendingData = function (data) {
  17678. this._pendingData.push(data);
  17679. };
  17680. Scene.prototype._removePendingData = function (data) {
  17681. var index = this._pendingData.indexOf(data);
  17682. if (index !== -1) {
  17683. this._pendingData.splice(index, 1);
  17684. }
  17685. };
  17686. Scene.prototype.getWaitingItemsCount = function () {
  17687. return this._pendingData.length;
  17688. };
  17689. /**
  17690. * Registers a function to be executed when the scene is ready.
  17691. * @param {Function} func - the function to be executed.
  17692. */
  17693. Scene.prototype.executeWhenReady = function (func) {
  17694. var _this = this;
  17695. this.onReadyObservable.add(func);
  17696. if (this._executeWhenReadyTimeoutId !== -1) {
  17697. return;
  17698. }
  17699. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17700. _this._checkIsReady();
  17701. }, 150);
  17702. };
  17703. Scene.prototype._checkIsReady = function () {
  17704. var _this = this;
  17705. if (this.isReady()) {
  17706. this.onReadyObservable.notifyObservers(this);
  17707. this.onReadyObservable.clear();
  17708. this._executeWhenReadyTimeoutId = -1;
  17709. return;
  17710. }
  17711. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17712. _this._checkIsReady();
  17713. }, 150);
  17714. };
  17715. // Animations
  17716. /**
  17717. * Will start the animation sequence of a given target
  17718. * @param target - the target
  17719. * @param {number} from - from which frame should animation start
  17720. * @param {number} to - till which frame should animation run.
  17721. * @param {boolean} [loop] - should the animation loop
  17722. * @param {number} [speedRatio] - the speed in which to run the animation
  17723. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17724. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17725. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17726. * See BABYLON.Animatable
  17727. */
  17728. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17729. if (speedRatio === void 0) { speedRatio = 1.0; }
  17730. if (from > to && speedRatio > 0) {
  17731. speedRatio *= -1;
  17732. }
  17733. this.stopAnimation(target);
  17734. if (!animatable) {
  17735. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17736. }
  17737. // Local animations
  17738. if (target.animations) {
  17739. animatable.appendAnimations(target, target.animations);
  17740. }
  17741. // Children animations
  17742. if (target.getAnimatables) {
  17743. var animatables = target.getAnimatables();
  17744. for (var index = 0; index < animatables.length; index++) {
  17745. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17746. }
  17747. }
  17748. animatable.reset();
  17749. return animatable;
  17750. };
  17751. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17752. if (speedRatio === undefined) {
  17753. speedRatio = 1.0;
  17754. }
  17755. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17756. return animatable;
  17757. };
  17758. Scene.prototype.getAnimatableByTarget = function (target) {
  17759. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17760. if (this._activeAnimatables[index].target === target) {
  17761. return this._activeAnimatables[index];
  17762. }
  17763. }
  17764. return null;
  17765. };
  17766. Object.defineProperty(Scene.prototype, "Animatables", {
  17767. get: function () {
  17768. return this._activeAnimatables;
  17769. },
  17770. enumerable: true,
  17771. configurable: true
  17772. });
  17773. /**
  17774. * Will stop the animation of the given target
  17775. * @param target - the target
  17776. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17777. * @see beginAnimation
  17778. */
  17779. Scene.prototype.stopAnimation = function (target, animationName) {
  17780. var animatable = this.getAnimatableByTarget(target);
  17781. if (animatable) {
  17782. animatable.stop(animationName);
  17783. }
  17784. };
  17785. Scene.prototype._animate = function () {
  17786. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17787. return;
  17788. }
  17789. // Getting time
  17790. var now = BABYLON.Tools.Now;
  17791. if (!this._animationTimeLast) {
  17792. if (this._pendingData.length > 0) {
  17793. return;
  17794. }
  17795. this._animationTimeLast = now;
  17796. }
  17797. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17798. this._animationTime += deltaTime;
  17799. this._animationTimeLast = now;
  17800. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17801. this._activeAnimatables[index]._animate(this._animationTime);
  17802. }
  17803. };
  17804. // Matrix
  17805. Scene.prototype.getViewMatrix = function () {
  17806. return this._viewMatrix;
  17807. };
  17808. Scene.prototype.getProjectionMatrix = function () {
  17809. return this._projectionMatrix;
  17810. };
  17811. Scene.prototype.getTransformMatrix = function () {
  17812. return this._transformMatrix;
  17813. };
  17814. Scene.prototype.setTransformMatrix = function (view, projection) {
  17815. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17816. return;
  17817. }
  17818. this._viewUpdateFlag = view.updateFlag;
  17819. this._projectionUpdateFlag = projection.updateFlag;
  17820. this._viewMatrix = view;
  17821. this._projectionMatrix = projection;
  17822. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17823. // Update frustum
  17824. if (!this._frustumPlanes) {
  17825. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17826. }
  17827. else {
  17828. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17829. }
  17830. if (this._sceneUbo.useUbo) {
  17831. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17832. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17833. this._sceneUbo.update();
  17834. }
  17835. };
  17836. Scene.prototype.getSceneUniformBuffer = function () {
  17837. return this._sceneUbo;
  17838. };
  17839. // Methods
  17840. Scene.prototype.getUniqueId = function () {
  17841. var result = this._uniqueIdCounter;
  17842. this._uniqueIdCounter++;
  17843. return result;
  17844. };
  17845. Scene.prototype.addMesh = function (newMesh) {
  17846. newMesh.uniqueId = this.getUniqueId();
  17847. var position = this.meshes.push(newMesh);
  17848. //notify the collision coordinator
  17849. if (this.collisionCoordinator) {
  17850. this.collisionCoordinator.onMeshAdded(newMesh);
  17851. }
  17852. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17853. };
  17854. Scene.prototype.removeMesh = function (toRemove) {
  17855. var index = this.meshes.indexOf(toRemove);
  17856. if (index !== -1) {
  17857. // Remove from the scene if mesh found
  17858. this.meshes.splice(index, 1);
  17859. }
  17860. //notify the collision coordinator
  17861. if (this.collisionCoordinator) {
  17862. this.collisionCoordinator.onMeshRemoved(toRemove);
  17863. }
  17864. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17865. return index;
  17866. };
  17867. Scene.prototype.removeSkeleton = function (toRemove) {
  17868. var index = this.skeletons.indexOf(toRemove);
  17869. if (index !== -1) {
  17870. // Remove from the scene if found
  17871. this.skeletons.splice(index, 1);
  17872. }
  17873. return index;
  17874. };
  17875. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17876. var index = this.morphTargetManagers.indexOf(toRemove);
  17877. if (index !== -1) {
  17878. // Remove from the scene if found
  17879. this.morphTargetManagers.splice(index, 1);
  17880. }
  17881. return index;
  17882. };
  17883. Scene.prototype.removeLight = function (toRemove) {
  17884. var index = this.lights.indexOf(toRemove);
  17885. if (index !== -1) {
  17886. // Remove from the scene if mesh found
  17887. this.lights.splice(index, 1);
  17888. this.sortLightsByPriority();
  17889. }
  17890. this.onLightRemovedObservable.notifyObservers(toRemove);
  17891. return index;
  17892. };
  17893. Scene.prototype.removeCamera = function (toRemove) {
  17894. var index = this.cameras.indexOf(toRemove);
  17895. if (index !== -1) {
  17896. // Remove from the scene if mesh found
  17897. this.cameras.splice(index, 1);
  17898. }
  17899. // Remove from activeCameras
  17900. var index2 = this.activeCameras.indexOf(toRemove);
  17901. if (index2 !== -1) {
  17902. // Remove from the scene if mesh found
  17903. this.activeCameras.splice(index2, 1);
  17904. }
  17905. // Reset the activeCamera
  17906. if (this.activeCamera === toRemove) {
  17907. if (this.cameras.length > 0) {
  17908. this.activeCamera = this.cameras[0];
  17909. }
  17910. else {
  17911. this.activeCamera = null;
  17912. }
  17913. }
  17914. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17915. return index;
  17916. };
  17917. Scene.prototype.addLight = function (newLight) {
  17918. newLight.uniqueId = this.getUniqueId();
  17919. this.lights.push(newLight);
  17920. this.sortLightsByPriority();
  17921. this.onNewLightAddedObservable.notifyObservers(newLight);
  17922. };
  17923. Scene.prototype.sortLightsByPriority = function () {
  17924. if (this.requireLightSorting) {
  17925. this.lights.sort(BABYLON.Light.compareLightsPriority);
  17926. }
  17927. };
  17928. Scene.prototype.addCamera = function (newCamera) {
  17929. newCamera.uniqueId = this.getUniqueId();
  17930. var position = this.cameras.push(newCamera);
  17931. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17932. };
  17933. /**
  17934. * Switch active camera
  17935. * @param {Camera} newCamera - new active camera
  17936. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17937. */
  17938. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17939. if (attachControl === void 0) { attachControl = true; }
  17940. var canvas = this._engine.getRenderingCanvas();
  17941. this.activeCamera.detachControl(canvas);
  17942. this.activeCamera = newCamera;
  17943. if (attachControl) {
  17944. newCamera.attachControl(canvas);
  17945. }
  17946. };
  17947. /**
  17948. * sets the active camera of the scene using its ID
  17949. * @param {string} id - the camera's ID
  17950. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17951. * @see activeCamera
  17952. */
  17953. Scene.prototype.setActiveCameraByID = function (id) {
  17954. var camera = this.getCameraByID(id);
  17955. if (camera) {
  17956. this.activeCamera = camera;
  17957. return camera;
  17958. }
  17959. return null;
  17960. };
  17961. /**
  17962. * sets the active camera of the scene using its name
  17963. * @param {string} name - the camera's name
  17964. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17965. * @see activeCamera
  17966. */
  17967. Scene.prototype.setActiveCameraByName = function (name) {
  17968. var camera = this.getCameraByName(name);
  17969. if (camera) {
  17970. this.activeCamera = camera;
  17971. return camera;
  17972. }
  17973. return null;
  17974. };
  17975. /**
  17976. * get a material using its id
  17977. * @param {string} the material's ID
  17978. * @return {BABYLON.Material|null} the material or null if none found.
  17979. */
  17980. Scene.prototype.getMaterialByID = function (id) {
  17981. for (var index = 0; index < this.materials.length; index++) {
  17982. if (this.materials[index].id === id) {
  17983. return this.materials[index];
  17984. }
  17985. }
  17986. return null;
  17987. };
  17988. /**
  17989. * get a material using its name
  17990. * @param {string} the material's name
  17991. * @return {BABYLON.Material|null} the material or null if none found.
  17992. */
  17993. Scene.prototype.getMaterialByName = function (name) {
  17994. for (var index = 0; index < this.materials.length; index++) {
  17995. if (this.materials[index].name === name) {
  17996. return this.materials[index];
  17997. }
  17998. }
  17999. return null;
  18000. };
  18001. Scene.prototype.getLensFlareSystemByName = function (name) {
  18002. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18003. if (this.lensFlareSystems[index].name === name) {
  18004. return this.lensFlareSystems[index];
  18005. }
  18006. }
  18007. return null;
  18008. };
  18009. Scene.prototype.getLensFlareSystemByID = function (id) {
  18010. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18011. if (this.lensFlareSystems[index].id === id) {
  18012. return this.lensFlareSystems[index];
  18013. }
  18014. }
  18015. return null;
  18016. };
  18017. Scene.prototype.getCameraByID = function (id) {
  18018. for (var index = 0; index < this.cameras.length; index++) {
  18019. if (this.cameras[index].id === id) {
  18020. return this.cameras[index];
  18021. }
  18022. }
  18023. return null;
  18024. };
  18025. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18026. for (var index = 0; index < this.cameras.length; index++) {
  18027. if (this.cameras[index].uniqueId === uniqueId) {
  18028. return this.cameras[index];
  18029. }
  18030. }
  18031. return null;
  18032. };
  18033. /**
  18034. * get a camera using its name
  18035. * @param {string} the camera's name
  18036. * @return {BABYLON.Camera|null} the camera or null if none found.
  18037. */
  18038. Scene.prototype.getCameraByName = function (name) {
  18039. for (var index = 0; index < this.cameras.length; index++) {
  18040. if (this.cameras[index].name === name) {
  18041. return this.cameras[index];
  18042. }
  18043. }
  18044. return null;
  18045. };
  18046. /**
  18047. * get a bone using its id
  18048. * @param {string} the bone's id
  18049. * @return {BABYLON.Bone|null} the bone or null if not found
  18050. */
  18051. Scene.prototype.getBoneByID = function (id) {
  18052. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18053. var skeleton = this.skeletons[skeletonIndex];
  18054. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18055. if (skeleton.bones[boneIndex].id === id) {
  18056. return skeleton.bones[boneIndex];
  18057. }
  18058. }
  18059. }
  18060. return null;
  18061. };
  18062. /**
  18063. * get a bone using its id
  18064. * @param {string} the bone's name
  18065. * @return {BABYLON.Bone|null} the bone or null if not found
  18066. */
  18067. Scene.prototype.getBoneByName = function (name) {
  18068. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18069. var skeleton = this.skeletons[skeletonIndex];
  18070. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18071. if (skeleton.bones[boneIndex].name === name) {
  18072. return skeleton.bones[boneIndex];
  18073. }
  18074. }
  18075. }
  18076. return null;
  18077. };
  18078. /**
  18079. * get a light node using its name
  18080. * @param {string} the light's name
  18081. * @return {BABYLON.Light|null} the light or null if none found.
  18082. */
  18083. Scene.prototype.getLightByName = function (name) {
  18084. for (var index = 0; index < this.lights.length; index++) {
  18085. if (this.lights[index].name === name) {
  18086. return this.lights[index];
  18087. }
  18088. }
  18089. return null;
  18090. };
  18091. /**
  18092. * get a light node using its ID
  18093. * @param {string} the light's id
  18094. * @return {BABYLON.Light|null} the light or null if none found.
  18095. */
  18096. Scene.prototype.getLightByID = function (id) {
  18097. for (var index = 0; index < this.lights.length; index++) {
  18098. if (this.lights[index].id === id) {
  18099. return this.lights[index];
  18100. }
  18101. }
  18102. return null;
  18103. };
  18104. /**
  18105. * get a light node using its scene-generated unique ID
  18106. * @param {number} the light's unique id
  18107. * @return {BABYLON.Light|null} the light or null if none found.
  18108. */
  18109. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18110. for (var index = 0; index < this.lights.length; index++) {
  18111. if (this.lights[index].uniqueId === uniqueId) {
  18112. return this.lights[index];
  18113. }
  18114. }
  18115. return null;
  18116. };
  18117. /**
  18118. * get a particle system by id
  18119. * @param id {number} the particle system id
  18120. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  18121. */
  18122. Scene.prototype.getParticleSystemByID = function (id) {
  18123. for (var index = 0; index < this.particleSystems.length; index++) {
  18124. if (this.particleSystems[index].id === id) {
  18125. return this.particleSystems[index];
  18126. }
  18127. }
  18128. return null;
  18129. };
  18130. /**
  18131. * get a geometry using its ID
  18132. * @param {string} the geometry's id
  18133. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18134. */
  18135. Scene.prototype.getGeometryByID = function (id) {
  18136. for (var index = 0; index < this._geometries.length; index++) {
  18137. if (this._geometries[index].id === id) {
  18138. return this._geometries[index];
  18139. }
  18140. }
  18141. return null;
  18142. };
  18143. /**
  18144. * add a new geometry to this scene.
  18145. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18146. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18147. * @return {boolean} was the geometry added or not
  18148. */
  18149. Scene.prototype.pushGeometry = function (geometry, force) {
  18150. if (!force && this.getGeometryByID(geometry.id)) {
  18151. return false;
  18152. }
  18153. this._geometries.push(geometry);
  18154. //notify the collision coordinator
  18155. if (this.collisionCoordinator) {
  18156. this.collisionCoordinator.onGeometryAdded(geometry);
  18157. }
  18158. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18159. return true;
  18160. };
  18161. /**
  18162. * Removes an existing geometry
  18163. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18164. * @return {boolean} was the geometry removed or not
  18165. */
  18166. Scene.prototype.removeGeometry = function (geometry) {
  18167. var index = this._geometries.indexOf(geometry);
  18168. if (index > -1) {
  18169. this._geometries.splice(index, 1);
  18170. //notify the collision coordinator
  18171. if (this.collisionCoordinator) {
  18172. this.collisionCoordinator.onGeometryDeleted(geometry);
  18173. }
  18174. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18175. return true;
  18176. }
  18177. return false;
  18178. };
  18179. Scene.prototype.getGeometries = function () {
  18180. return this._geometries;
  18181. };
  18182. /**
  18183. * Get the first added mesh found of a given ID
  18184. * @param {string} id - the id to search for
  18185. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18186. */
  18187. Scene.prototype.getMeshByID = function (id) {
  18188. for (var index = 0; index < this.meshes.length; index++) {
  18189. if (this.meshes[index].id === id) {
  18190. return this.meshes[index];
  18191. }
  18192. }
  18193. return null;
  18194. };
  18195. Scene.prototype.getMeshesByID = function (id) {
  18196. return this.meshes.filter(function (m) {
  18197. return m.id === id;
  18198. });
  18199. };
  18200. /**
  18201. * Get a mesh with its auto-generated unique id
  18202. * @param {number} uniqueId - the unique id to search for
  18203. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18204. */
  18205. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18206. for (var index = 0; index < this.meshes.length; index++) {
  18207. if (this.meshes[index].uniqueId === uniqueId) {
  18208. return this.meshes[index];
  18209. }
  18210. }
  18211. return null;
  18212. };
  18213. /**
  18214. * Get a the last added mesh found of a given ID
  18215. * @param {string} id - the id to search for
  18216. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18217. */
  18218. Scene.prototype.getLastMeshByID = function (id) {
  18219. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18220. if (this.meshes[index].id === id) {
  18221. return this.meshes[index];
  18222. }
  18223. }
  18224. return null;
  18225. };
  18226. /**
  18227. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18228. * @param {string} id - the id to search for
  18229. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18230. */
  18231. Scene.prototype.getLastEntryByID = function (id) {
  18232. var index;
  18233. for (index = this.meshes.length - 1; index >= 0; index--) {
  18234. if (this.meshes[index].id === id) {
  18235. return this.meshes[index];
  18236. }
  18237. }
  18238. for (index = this.cameras.length - 1; index >= 0; index--) {
  18239. if (this.cameras[index].id === id) {
  18240. return this.cameras[index];
  18241. }
  18242. }
  18243. for (index = this.lights.length - 1; index >= 0; index--) {
  18244. if (this.lights[index].id === id) {
  18245. return this.lights[index];
  18246. }
  18247. }
  18248. return null;
  18249. };
  18250. Scene.prototype.getNodeByID = function (id) {
  18251. var mesh = this.getMeshByID(id);
  18252. if (mesh) {
  18253. return mesh;
  18254. }
  18255. var light = this.getLightByID(id);
  18256. if (light) {
  18257. return light;
  18258. }
  18259. var camera = this.getCameraByID(id);
  18260. if (camera) {
  18261. return camera;
  18262. }
  18263. var bone = this.getBoneByID(id);
  18264. return bone;
  18265. };
  18266. Scene.prototype.getNodeByName = function (name) {
  18267. var mesh = this.getMeshByName(name);
  18268. if (mesh) {
  18269. return mesh;
  18270. }
  18271. var light = this.getLightByName(name);
  18272. if (light) {
  18273. return light;
  18274. }
  18275. var camera = this.getCameraByName(name);
  18276. if (camera) {
  18277. return camera;
  18278. }
  18279. var bone = this.getBoneByName(name);
  18280. return bone;
  18281. };
  18282. Scene.prototype.getMeshByName = function (name) {
  18283. for (var index = 0; index < this.meshes.length; index++) {
  18284. if (this.meshes[index].name === name) {
  18285. return this.meshes[index];
  18286. }
  18287. }
  18288. return null;
  18289. };
  18290. Scene.prototype.getSoundByName = function (name) {
  18291. var index;
  18292. if (BABYLON.AudioEngine) {
  18293. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18294. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18295. return this.mainSoundTrack.soundCollection[index];
  18296. }
  18297. }
  18298. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18299. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18300. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18301. return this.soundTracks[sdIndex].soundCollection[index];
  18302. }
  18303. }
  18304. }
  18305. }
  18306. return null;
  18307. };
  18308. Scene.prototype.getLastSkeletonByID = function (id) {
  18309. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18310. if (this.skeletons[index].id === id) {
  18311. return this.skeletons[index];
  18312. }
  18313. }
  18314. return null;
  18315. };
  18316. Scene.prototype.getSkeletonById = function (id) {
  18317. for (var index = 0; index < this.skeletons.length; index++) {
  18318. if (this.skeletons[index].id === id) {
  18319. return this.skeletons[index];
  18320. }
  18321. }
  18322. return null;
  18323. };
  18324. Scene.prototype.getSkeletonByName = function (name) {
  18325. for (var index = 0; index < this.skeletons.length; index++) {
  18326. if (this.skeletons[index].name === name) {
  18327. return this.skeletons[index];
  18328. }
  18329. }
  18330. return null;
  18331. };
  18332. Scene.prototype.getMorphTargetManagerById = function (id) {
  18333. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18334. if (this.morphTargetManagers[index].uniqueId === id) {
  18335. return this.morphTargetManagers[index];
  18336. }
  18337. }
  18338. return null;
  18339. };
  18340. Scene.prototype.isActiveMesh = function (mesh) {
  18341. return (this._activeMeshes.indexOf(mesh) !== -1);
  18342. };
  18343. /**
  18344. * Return a the first highlight layer of the scene with a given name.
  18345. * @param name The name of the highlight layer to look for.
  18346. * @return The highlight layer if found otherwise null.
  18347. */
  18348. Scene.prototype.getHighlightLayerByName = function (name) {
  18349. for (var index = 0; index < this.highlightLayers.length; index++) {
  18350. if (this.highlightLayers[index].name === name) {
  18351. return this.highlightLayers[index];
  18352. }
  18353. }
  18354. return null;
  18355. };
  18356. Object.defineProperty(Scene.prototype, "uid", {
  18357. /**
  18358. * Return a unique id as a string which can serve as an identifier for the scene
  18359. */
  18360. get: function () {
  18361. if (!this._uid) {
  18362. this._uid = BABYLON.Tools.RandomId();
  18363. }
  18364. return this._uid;
  18365. },
  18366. enumerable: true,
  18367. configurable: true
  18368. });
  18369. /**
  18370. * Add an externaly attached data from its key.
  18371. * This method call will fail and return false, if such key already exists.
  18372. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18373. * @param key the unique key that identifies the data
  18374. * @param data the data object to associate to the key for this Engine instance
  18375. * @return true if no such key were already present and the data was added successfully, false otherwise
  18376. */
  18377. Scene.prototype.addExternalData = function (key, data) {
  18378. if (!this._externalData) {
  18379. this._externalData = new BABYLON.StringDictionary();
  18380. }
  18381. return this._externalData.add(key, data);
  18382. };
  18383. /**
  18384. * Get an externaly attached data from its key
  18385. * @param key the unique key that identifies the data
  18386. * @return the associated data, if present (can be null), or undefined if not present
  18387. */
  18388. Scene.prototype.getExternalData = function (key) {
  18389. if (!this._externalData) {
  18390. return null;
  18391. }
  18392. return this._externalData.get(key);
  18393. };
  18394. /**
  18395. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18396. * @param key the unique key that identifies the data
  18397. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18398. * @return the associated data, can be null if the factory returned null.
  18399. */
  18400. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18401. if (!this._externalData) {
  18402. this._externalData = new BABYLON.StringDictionary();
  18403. }
  18404. return this._externalData.getOrAddWithFactory(key, factory);
  18405. };
  18406. /**
  18407. * Remove an externaly attached data from the Engine instance
  18408. * @param key the unique key that identifies the data
  18409. * @return true if the data was successfully removed, false if it doesn't exist
  18410. */
  18411. Scene.prototype.removeExternalData = function (key) {
  18412. return this._externalData.remove(key);
  18413. };
  18414. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18415. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18416. var material = subMesh.getMaterial();
  18417. if (mesh.showSubMeshesBoundingBox) {
  18418. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18419. }
  18420. if (material) {
  18421. // Render targets
  18422. if (material.getRenderTargetTextures) {
  18423. if (this._processedMaterials.indexOf(material) === -1) {
  18424. this._processedMaterials.push(material);
  18425. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18426. }
  18427. }
  18428. // Dispatch
  18429. this._activeIndices.addCount(subMesh.indexCount, false);
  18430. this._renderingManager.dispatch(subMesh);
  18431. }
  18432. }
  18433. };
  18434. Scene.prototype._isInIntermediateRendering = function () {
  18435. return this._intermediateRendering;
  18436. };
  18437. Scene.prototype._evaluateActiveMeshes = function () {
  18438. this.activeCamera._activeMeshes.reset();
  18439. this._activeMeshes.reset();
  18440. this._renderingManager.reset();
  18441. this._processedMaterials.reset();
  18442. this._activeParticleSystems.reset();
  18443. this._activeSkeletons.reset();
  18444. this._softwareSkinnedMeshes.reset();
  18445. if (this._boundingBoxRenderer) {
  18446. this._boundingBoxRenderer.reset();
  18447. }
  18448. // Meshes
  18449. var meshes;
  18450. var len;
  18451. if (this._selectionOctree) {
  18452. var selection = this._selectionOctree.select(this._frustumPlanes);
  18453. meshes = selection.data;
  18454. len = selection.length;
  18455. }
  18456. else {
  18457. len = this.meshes.length;
  18458. meshes = this.meshes;
  18459. }
  18460. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18461. var mesh = meshes[meshIndex];
  18462. if (mesh.isBlocked) {
  18463. continue;
  18464. }
  18465. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18466. if (!mesh.isReady() || !mesh.isEnabled()) {
  18467. continue;
  18468. }
  18469. mesh.computeWorldMatrix();
  18470. // Intersections
  18471. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18472. this._meshesForIntersections.pushNoDuplicate(mesh);
  18473. }
  18474. // Switch to current LOD
  18475. var meshLOD = mesh.getLOD(this.activeCamera);
  18476. if (!meshLOD) {
  18477. continue;
  18478. }
  18479. mesh._preActivate();
  18480. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18481. this._activeMeshes.push(mesh);
  18482. this.activeCamera._activeMeshes.push(mesh);
  18483. mesh._activate(this._renderId);
  18484. if (meshLOD !== mesh) {
  18485. meshLOD._activate(this._renderId);
  18486. }
  18487. this._activeMesh(mesh, meshLOD);
  18488. }
  18489. }
  18490. // Particle systems
  18491. this._particlesDuration.beginMonitoring();
  18492. var beforeParticlesDate = BABYLON.Tools.Now;
  18493. if (this.particlesEnabled) {
  18494. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18495. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18496. var particleSystem = this.particleSystems[particleIndex];
  18497. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18498. continue;
  18499. }
  18500. var emitter = particleSystem.emitter;
  18501. if (!emitter.position || emitter.isEnabled()) {
  18502. this._activeParticleSystems.push(particleSystem);
  18503. particleSystem.animate();
  18504. this._renderingManager.dispatchParticles(particleSystem);
  18505. }
  18506. }
  18507. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18508. }
  18509. this._particlesDuration.endMonitoring(false);
  18510. };
  18511. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18512. if (mesh.skeleton && this.skeletonsEnabled) {
  18513. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18514. mesh.skeleton.prepare();
  18515. }
  18516. if (!mesh.computeBonesUsingShaders) {
  18517. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18518. }
  18519. }
  18520. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18521. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18522. }
  18523. if (mesh && mesh.subMeshes) {
  18524. // Submeshes Octrees
  18525. var len;
  18526. var subMeshes;
  18527. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18528. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18529. len = intersections.length;
  18530. subMeshes = intersections.data;
  18531. }
  18532. else {
  18533. subMeshes = mesh.subMeshes;
  18534. len = subMeshes.length;
  18535. }
  18536. for (var subIndex = 0; subIndex < len; subIndex++) {
  18537. var subMesh = subMeshes[subIndex];
  18538. this._evaluateSubMesh(subMesh, mesh);
  18539. }
  18540. }
  18541. };
  18542. Scene.prototype.updateTransformMatrix = function (force) {
  18543. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18544. };
  18545. Scene.prototype._renderForCamera = function (camera) {
  18546. var engine = this._engine;
  18547. var startTime = BABYLON.Tools.Now;
  18548. this.activeCamera = camera;
  18549. if (!this.activeCamera)
  18550. throw new Error("Active camera not set");
  18551. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18552. // Viewport
  18553. engine.setViewport(this.activeCamera.viewport);
  18554. // Camera
  18555. this.resetCachedMaterial();
  18556. this._renderId++;
  18557. this.updateTransformMatrix();
  18558. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18559. // Meshes
  18560. this._evaluateActiveMeshesDuration.beginMonitoring();
  18561. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18562. this._evaluateActiveMeshes();
  18563. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18564. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18565. // Software skinning
  18566. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18567. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18568. mesh.applySkeleton(mesh.skeleton);
  18569. }
  18570. // Render targets
  18571. this._renderTargetsDuration.beginMonitoring();
  18572. var needsRestoreFrameBuffer = false;
  18573. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18574. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18575. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18576. }
  18577. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18578. this._intermediateRendering = true;
  18579. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18580. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18581. var renderTarget = this._renderTargets.data[renderIndex];
  18582. if (renderTarget._shouldRender()) {
  18583. this._renderId++;
  18584. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18585. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18586. }
  18587. }
  18588. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18589. this._intermediateRendering = false;
  18590. this._renderId++;
  18591. needsRestoreFrameBuffer = true; // Restore back buffer
  18592. }
  18593. // Render HighlightLayer Texture
  18594. var stencilState = this._engine.getStencilBuffer();
  18595. var renderhighlights = false;
  18596. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18597. this._intermediateRendering = true;
  18598. for (var i = 0; i < this.highlightLayers.length; i++) {
  18599. var highlightLayer = this.highlightLayers[i];
  18600. if (highlightLayer.shouldRender() &&
  18601. (!highlightLayer.camera ||
  18602. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18603. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18604. renderhighlights = true;
  18605. var renderTarget = highlightLayer._mainTexture;
  18606. if (renderTarget._shouldRender()) {
  18607. this._renderId++;
  18608. renderTarget.render(false, false);
  18609. needsRestoreFrameBuffer = true;
  18610. }
  18611. }
  18612. }
  18613. this._intermediateRendering = false;
  18614. this._renderId++;
  18615. }
  18616. if (needsRestoreFrameBuffer) {
  18617. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18618. }
  18619. this._renderTargetsDuration.endMonitoring(false);
  18620. // Prepare Frame
  18621. this.postProcessManager._prepareFrame();
  18622. this._renderDuration.beginMonitoring();
  18623. // Backgrounds
  18624. var layerIndex;
  18625. var layer;
  18626. if (this.layers.length) {
  18627. engine.setDepthBuffer(false);
  18628. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18629. layer = this.layers[layerIndex];
  18630. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18631. layer.render();
  18632. }
  18633. }
  18634. engine.setDepthBuffer(true);
  18635. }
  18636. // Render
  18637. BABYLON.Tools.StartPerformanceCounter("Main render");
  18638. // Activate HighlightLayer stencil
  18639. if (renderhighlights) {
  18640. this._engine.setStencilBuffer(true);
  18641. }
  18642. this._renderingManager.render(null, null, true, true);
  18643. // Restore HighlightLayer stencil
  18644. if (renderhighlights) {
  18645. this._engine.setStencilBuffer(stencilState);
  18646. }
  18647. BABYLON.Tools.EndPerformanceCounter("Main render");
  18648. // Bounding boxes
  18649. if (this._boundingBoxRenderer) {
  18650. this._boundingBoxRenderer.render();
  18651. }
  18652. // Lens flares
  18653. if (this.lensFlaresEnabled) {
  18654. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18655. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18656. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18657. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18658. lensFlareSystem.render();
  18659. }
  18660. }
  18661. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18662. }
  18663. // Foregrounds
  18664. if (this.layers.length) {
  18665. engine.setDepthBuffer(false);
  18666. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18667. layer = this.layers[layerIndex];
  18668. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18669. layer.render();
  18670. }
  18671. }
  18672. engine.setDepthBuffer(true);
  18673. }
  18674. // Highlight Layer
  18675. if (renderhighlights) {
  18676. engine.setDepthBuffer(false);
  18677. for (var i = 0; i < this.highlightLayers.length; i++) {
  18678. if (this.highlightLayers[i].shouldRender()) {
  18679. this.highlightLayers[i].render();
  18680. }
  18681. }
  18682. engine.setDepthBuffer(true);
  18683. }
  18684. this._renderDuration.endMonitoring(false);
  18685. // Finalize frame
  18686. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18687. // Update camera
  18688. this.activeCamera._updateFromScene();
  18689. // Reset some special arrays
  18690. this._renderTargets.reset();
  18691. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18692. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18693. };
  18694. Scene.prototype._processSubCameras = function (camera) {
  18695. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18696. this._renderForCamera(camera);
  18697. return;
  18698. }
  18699. // rig cameras
  18700. for (var index = 0; index < camera._rigCameras.length; index++) {
  18701. this._renderForCamera(camera._rigCameras[index]);
  18702. }
  18703. this.activeCamera = camera;
  18704. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18705. // Update camera
  18706. this.activeCamera._updateFromScene();
  18707. };
  18708. Scene.prototype._checkIntersections = function () {
  18709. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18710. var sourceMesh = this._meshesForIntersections.data[index];
  18711. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18712. var action = sourceMesh.actionManager.actions[actionIndex];
  18713. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18714. var parameters = action.getTriggerParameter();
  18715. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18716. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18717. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18718. if (areIntersecting && currentIntersectionInProgress === -1) {
  18719. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18720. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18721. sourceMesh._intersectionsInProgress.push(otherMesh);
  18722. }
  18723. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18724. sourceMesh._intersectionsInProgress.push(otherMesh);
  18725. }
  18726. }
  18727. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18728. //They intersected, and now they don't.
  18729. //is this trigger an exit trigger? execute an event.
  18730. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18731. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18732. }
  18733. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18734. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18735. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18736. }
  18737. }
  18738. }
  18739. }
  18740. }
  18741. };
  18742. Scene.prototype.render = function () {
  18743. if (this.isDisposed) {
  18744. return;
  18745. }
  18746. this._lastFrameDuration.beginMonitoring();
  18747. this._particlesDuration.fetchNewFrame();
  18748. this._spritesDuration.fetchNewFrame();
  18749. this._activeParticles.fetchNewFrame();
  18750. this._renderDuration.fetchNewFrame();
  18751. this._renderTargetsDuration.fetchNewFrame();
  18752. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18753. this._totalVertices.fetchNewFrame();
  18754. this._activeIndices.fetchNewFrame();
  18755. this._activeBones.fetchNewFrame();
  18756. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18757. this._meshesForIntersections.reset();
  18758. this.resetCachedMaterial();
  18759. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18760. // Actions
  18761. if (this.actionManager) {
  18762. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18763. }
  18764. //Simplification Queue
  18765. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18766. this.simplificationQueue.executeNext();
  18767. }
  18768. if (this._engine.isDeterministicLockStep()) {
  18769. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18770. var defaultTimeStep = (60.0 / 1000.0);
  18771. if (this._physicsEngine) {
  18772. defaultTimeStep = this._physicsEngine.getTimeStep();
  18773. }
  18774. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18775. this._timeAccumulator += deltaTime;
  18776. // compute the amount of fixed steps we should have taken since the last step
  18777. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  18778. internalSteps = Math.min(internalSteps, maxSubSteps);
  18779. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  18780. this.onBeforeStepObservable.notifyObservers(this);
  18781. // Animations
  18782. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  18783. this._animate();
  18784. // Physics
  18785. if (this._physicsEngine) {
  18786. BABYLON.Tools.StartPerformanceCounter("Physics");
  18787. this._physicsEngine._step(defaultTimeStep);
  18788. BABYLON.Tools.EndPerformanceCounter("Physics");
  18789. }
  18790. this._timeAccumulator -= defaultTimeStep;
  18791. this.onAfterStepObservable.notifyObservers(this);
  18792. this._currentStepId++;
  18793. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  18794. // Q: can this be optimized by putting some code in the afterStep callback?
  18795. // I had to put this code here, otherwise mesh attached to bones of another mesh skeleton,
  18796. // would return incorrect positions for internal stepIds (non-rendered steps)
  18797. this._evaluateActiveMeshes();
  18798. }
  18799. }
  18800. }
  18801. else {
  18802. // Animations
  18803. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18804. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18805. this._animate();
  18806. // Physics
  18807. if (this._physicsEngine) {
  18808. BABYLON.Tools.StartPerformanceCounter("Physics");
  18809. this._physicsEngine._step(deltaTime / 1000.0);
  18810. BABYLON.Tools.EndPerformanceCounter("Physics");
  18811. }
  18812. }
  18813. // Before render
  18814. this.onBeforeRenderObservable.notifyObservers(this);
  18815. // Customs render targets
  18816. this._renderTargetsDuration.beginMonitoring();
  18817. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18818. var engine = this.getEngine();
  18819. var currentActiveCamera = this.activeCamera;
  18820. if (this.renderTargetsEnabled) {
  18821. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18822. this._intermediateRendering = true;
  18823. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18824. var renderTarget = this.customRenderTargets[customIndex];
  18825. if (renderTarget._shouldRender()) {
  18826. this._renderId++;
  18827. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18828. if (!this.activeCamera)
  18829. throw new Error("Active camera not set");
  18830. // Viewport
  18831. engine.setViewport(this.activeCamera.viewport);
  18832. // Camera
  18833. this.updateTransformMatrix();
  18834. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18835. }
  18836. }
  18837. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18838. this._intermediateRendering = false;
  18839. this._renderId++;
  18840. }
  18841. // Restore back buffer
  18842. if (this.customRenderTargets.length > 0) {
  18843. engine.restoreDefaultFramebuffer();
  18844. }
  18845. this._renderTargetsDuration.endMonitoring();
  18846. this.activeCamera = currentActiveCamera;
  18847. // Procedural textures
  18848. if (this.proceduralTexturesEnabled) {
  18849. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18850. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18851. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18852. if (proceduralTexture._shouldRender()) {
  18853. proceduralTexture.render();
  18854. }
  18855. }
  18856. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18857. }
  18858. // Clear
  18859. if (this.autoClearDepthAndStencil || this.autoClear) {
  18860. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  18861. }
  18862. // Shadows
  18863. if (this.shadowsEnabled) {
  18864. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18865. var light = this.lights[lightIndex];
  18866. var shadowGenerator = light.getShadowGenerator();
  18867. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  18868. var shadowMap = shadowGenerator.getShadowMap();
  18869. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  18870. this._renderTargets.push(shadowMap);
  18871. }
  18872. }
  18873. }
  18874. }
  18875. // Depth renderer
  18876. if (this._depthRenderer) {
  18877. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18878. }
  18879. // Geometry renderer
  18880. if (this._geometryBufferRenderer) {
  18881. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  18882. }
  18883. // RenderPipeline
  18884. if (this._postProcessRenderPipelineManager) {
  18885. this._postProcessRenderPipelineManager.update();
  18886. }
  18887. // Multi-cameras?
  18888. if (this.activeCameras.length > 0) {
  18889. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18890. if (cameraIndex > 0) {
  18891. this._engine.clear(null, false, true, true);
  18892. }
  18893. this._processSubCameras(this.activeCameras[cameraIndex]);
  18894. }
  18895. }
  18896. else {
  18897. if (!this.activeCamera) {
  18898. throw new Error("No camera defined");
  18899. }
  18900. this._processSubCameras(this.activeCamera);
  18901. }
  18902. // Intersection checks
  18903. this._checkIntersections();
  18904. // Update the audio listener attached to the camera
  18905. if (BABYLON.AudioEngine) {
  18906. this._updateAudioParameters();
  18907. }
  18908. // After render
  18909. if (this.afterRender) {
  18910. this.afterRender();
  18911. }
  18912. this.onAfterRenderObservable.notifyObservers(this);
  18913. // Cleaning
  18914. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18915. this._toBeDisposed.data[index].dispose();
  18916. this._toBeDisposed[index] = null;
  18917. }
  18918. this._toBeDisposed.reset();
  18919. if (this.dumpNextRenderTargets) {
  18920. this.dumpNextRenderTargets = false;
  18921. }
  18922. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18923. this._lastFrameDuration.endMonitoring();
  18924. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18925. this._totalLightsCounter.addCount(this.lights.length, true);
  18926. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18927. this._totalTexturesCounter.addCount(this.textures.length, true);
  18928. this._activeBones.addCount(0, true);
  18929. this._activeIndices.addCount(0, true);
  18930. this._activeParticles.addCount(0, true);
  18931. };
  18932. Scene.prototype._updateAudioParameters = function () {
  18933. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18934. return;
  18935. }
  18936. var listeningCamera;
  18937. var audioEngine = BABYLON.Engine.audioEngine;
  18938. if (this.activeCameras.length > 0) {
  18939. listeningCamera = this.activeCameras[0];
  18940. }
  18941. else {
  18942. listeningCamera = this.activeCamera;
  18943. }
  18944. if (listeningCamera && audioEngine.canUseWebAudio) {
  18945. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18946. // for VR cameras
  18947. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  18948. listeningCamera = listeningCamera.rigCameras[0];
  18949. }
  18950. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18951. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18952. cameraDirection.normalize();
  18953. // To avoid some errors on GearVR
  18954. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  18955. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18956. }
  18957. var i;
  18958. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18959. var sound = this.mainSoundTrack.soundCollection[i];
  18960. if (sound.useCustomAttenuation) {
  18961. sound.updateDistanceFromListener();
  18962. }
  18963. }
  18964. for (i = 0; i < this.soundTracks.length; i++) {
  18965. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18966. sound = this.soundTracks[i].soundCollection[j];
  18967. if (sound.useCustomAttenuation) {
  18968. sound.updateDistanceFromListener();
  18969. }
  18970. }
  18971. }
  18972. }
  18973. };
  18974. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18975. // Audio
  18976. get: function () {
  18977. return this._audioEnabled;
  18978. },
  18979. set: function (value) {
  18980. this._audioEnabled = value;
  18981. if (BABYLON.AudioEngine) {
  18982. if (this._audioEnabled) {
  18983. this._enableAudio();
  18984. }
  18985. else {
  18986. this._disableAudio();
  18987. }
  18988. }
  18989. },
  18990. enumerable: true,
  18991. configurable: true
  18992. });
  18993. Scene.prototype._disableAudio = function () {
  18994. var i;
  18995. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18996. this.mainSoundTrack.soundCollection[i].pause();
  18997. }
  18998. for (i = 0; i < this.soundTracks.length; i++) {
  18999. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19000. this.soundTracks[i].soundCollection[j].pause();
  19001. }
  19002. }
  19003. };
  19004. Scene.prototype._enableAudio = function () {
  19005. var i;
  19006. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19007. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19008. this.mainSoundTrack.soundCollection[i].play();
  19009. }
  19010. }
  19011. for (i = 0; i < this.soundTracks.length; i++) {
  19012. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19013. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19014. this.soundTracks[i].soundCollection[j].play();
  19015. }
  19016. }
  19017. }
  19018. };
  19019. Object.defineProperty(Scene.prototype, "headphone", {
  19020. get: function () {
  19021. return this._headphone;
  19022. },
  19023. set: function (value) {
  19024. this._headphone = value;
  19025. if (BABYLON.AudioEngine) {
  19026. if (this._headphone) {
  19027. this._switchAudioModeForHeadphones();
  19028. }
  19029. else {
  19030. this._switchAudioModeForNormalSpeakers();
  19031. }
  19032. }
  19033. },
  19034. enumerable: true,
  19035. configurable: true
  19036. });
  19037. Scene.prototype._switchAudioModeForHeadphones = function () {
  19038. this.mainSoundTrack.switchPanningModelToHRTF();
  19039. for (var i = 0; i < this.soundTracks.length; i++) {
  19040. this.soundTracks[i].switchPanningModelToHRTF();
  19041. }
  19042. };
  19043. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19044. this.mainSoundTrack.switchPanningModelToEqualPower();
  19045. for (var i = 0; i < this.soundTracks.length; i++) {
  19046. this.soundTracks[i].switchPanningModelToEqualPower();
  19047. }
  19048. };
  19049. Scene.prototype.enableDepthRenderer = function () {
  19050. if (this._depthRenderer) {
  19051. return this._depthRenderer;
  19052. }
  19053. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19054. return this._depthRenderer;
  19055. };
  19056. Scene.prototype.disableDepthRenderer = function () {
  19057. if (!this._depthRenderer) {
  19058. return;
  19059. }
  19060. this._depthRenderer.dispose();
  19061. this._depthRenderer = null;
  19062. };
  19063. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  19064. if (ratio === void 0) { ratio = 1; }
  19065. if (this._geometryBufferRenderer) {
  19066. return this._geometryBufferRenderer;
  19067. }
  19068. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  19069. if (!this._geometryBufferRenderer.isSupported) {
  19070. this._geometryBufferRenderer = null;
  19071. }
  19072. return this._geometryBufferRenderer;
  19073. };
  19074. Scene.prototype.disableGeometryBufferRenderer = function () {
  19075. if (!this._geometryBufferRenderer) {
  19076. return;
  19077. }
  19078. this._geometryBufferRenderer.dispose();
  19079. this._geometryBufferRenderer = null;
  19080. };
  19081. Scene.prototype.freezeMaterials = function () {
  19082. for (var i = 0; i < this.materials.length; i++) {
  19083. this.materials[i].freeze();
  19084. }
  19085. };
  19086. Scene.prototype.unfreezeMaterials = function () {
  19087. for (var i = 0; i < this.materials.length; i++) {
  19088. this.materials[i].unfreeze();
  19089. }
  19090. };
  19091. Scene.prototype.dispose = function () {
  19092. this.beforeRender = null;
  19093. this.afterRender = null;
  19094. this.skeletons = [];
  19095. this.morphTargetManagers = [];
  19096. this.importedMeshesFiles = new Array();
  19097. this.resetCachedMaterial();
  19098. if (this._depthRenderer) {
  19099. this._depthRenderer.dispose();
  19100. }
  19101. if (this._gamepadManager) {
  19102. this._gamepadManager.dispose();
  19103. this._gamepadManager = null;
  19104. }
  19105. // Smart arrays
  19106. if (this.activeCamera) {
  19107. this.activeCamera._activeMeshes.dispose();
  19108. this.activeCamera = null;
  19109. }
  19110. this._activeMeshes.dispose();
  19111. this._renderingManager.dispose();
  19112. this._processedMaterials.dispose();
  19113. this._activeParticleSystems.dispose();
  19114. this._activeSkeletons.dispose();
  19115. this._softwareSkinnedMeshes.dispose();
  19116. this._renderTargets.dispose();
  19117. if (this._boundingBoxRenderer) {
  19118. this._boundingBoxRenderer.dispose();
  19119. }
  19120. this._meshesForIntersections.dispose();
  19121. this._toBeDisposed.dispose();
  19122. // Debug layer
  19123. if (this._debugLayer) {
  19124. this._debugLayer.hide();
  19125. }
  19126. // Events
  19127. this.onDisposeObservable.notifyObservers(this);
  19128. this.onDisposeObservable.clear();
  19129. this.onBeforeRenderObservable.clear();
  19130. this.onAfterRenderObservable.clear();
  19131. this.detachControl();
  19132. // Release sounds & sounds tracks
  19133. if (BABYLON.AudioEngine) {
  19134. this.disposeSounds();
  19135. }
  19136. // VR Helper
  19137. if (this.VRHelper) {
  19138. this.VRHelper.dispose();
  19139. }
  19140. // Detach cameras
  19141. var canvas = this._engine.getRenderingCanvas();
  19142. var index;
  19143. for (index = 0; index < this.cameras.length; index++) {
  19144. this.cameras[index].detachControl(canvas);
  19145. }
  19146. // Release lights
  19147. while (this.lights.length) {
  19148. this.lights[0].dispose();
  19149. }
  19150. // Release meshes
  19151. while (this.meshes.length) {
  19152. this.meshes[0].dispose(true);
  19153. }
  19154. // Release cameras
  19155. while (this.cameras.length) {
  19156. this.cameras[0].dispose();
  19157. }
  19158. // Release materials
  19159. if (this.defaultMaterial) {
  19160. this.defaultMaterial.dispose();
  19161. }
  19162. while (this.multiMaterials.length) {
  19163. this.multiMaterials[0].dispose();
  19164. }
  19165. while (this.materials.length) {
  19166. this.materials[0].dispose();
  19167. }
  19168. // Release particles
  19169. while (this.particleSystems.length) {
  19170. this.particleSystems[0].dispose();
  19171. }
  19172. // Release sprites
  19173. while (this.spriteManagers.length) {
  19174. this.spriteManagers[0].dispose();
  19175. }
  19176. // Release postProcesses
  19177. while (this.postProcesses.length) {
  19178. this.postProcesses[0].dispose();
  19179. }
  19180. // Release layers
  19181. while (this.layers.length) {
  19182. this.layers[0].dispose();
  19183. }
  19184. while (this.highlightLayers.length) {
  19185. this.highlightLayers[0].dispose();
  19186. }
  19187. // Release textures
  19188. while (this.textures.length) {
  19189. this.textures[0].dispose();
  19190. }
  19191. // Release UBO
  19192. this._sceneUbo.dispose();
  19193. // Post-processes
  19194. this.postProcessManager.dispose();
  19195. if (this._postProcessRenderPipelineManager) {
  19196. this._postProcessRenderPipelineManager.dispose();
  19197. }
  19198. // Physics
  19199. if (this._physicsEngine) {
  19200. this.disablePhysicsEngine();
  19201. }
  19202. // Remove from engine
  19203. index = this._engine.scenes.indexOf(this);
  19204. if (index > -1) {
  19205. this._engine.scenes.splice(index, 1);
  19206. }
  19207. this._engine.wipeCaches();
  19208. this._engine = null;
  19209. this.defaultMaterial = null;
  19210. this.multiMaterials = null;
  19211. this.materials = null;
  19212. };
  19213. Object.defineProperty(Scene.prototype, "isDisposed", {
  19214. get: function () {
  19215. return !this._engine;
  19216. },
  19217. enumerable: true,
  19218. configurable: true
  19219. });
  19220. // Release sounds & sounds tracks
  19221. Scene.prototype.disposeSounds = function () {
  19222. this.mainSoundTrack.dispose();
  19223. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19224. this.soundTracks[scIndex].dispose();
  19225. }
  19226. };
  19227. // Octrees
  19228. Scene.prototype.getWorldExtends = function () {
  19229. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19230. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19231. for (var index = 0; index < this.meshes.length; index++) {
  19232. var mesh = this.meshes[index];
  19233. mesh.computeWorldMatrix(true);
  19234. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19235. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19236. BABYLON.Tools.CheckExtends(minBox, min, max);
  19237. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19238. }
  19239. return {
  19240. min: min,
  19241. max: max
  19242. };
  19243. };
  19244. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19245. if (maxCapacity === void 0) { maxCapacity = 64; }
  19246. if (maxDepth === void 0) { maxDepth = 2; }
  19247. if (!this._selectionOctree) {
  19248. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19249. }
  19250. var worldExtends = this.getWorldExtends();
  19251. // Update octree
  19252. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19253. return this._selectionOctree;
  19254. };
  19255. // Picking
  19256. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19257. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19258. var engine = this._engine;
  19259. if (!camera) {
  19260. if (!this.activeCamera)
  19261. throw new Error("Active camera not set");
  19262. camera = this.activeCamera;
  19263. }
  19264. var cameraViewport = camera.viewport;
  19265. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19266. // Moving coordinates to local viewport world
  19267. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19268. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19269. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19270. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19271. };
  19272. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19273. if (!BABYLON.PickingInfo) {
  19274. return null;
  19275. }
  19276. var engine = this._engine;
  19277. if (!camera) {
  19278. if (!this.activeCamera)
  19279. throw new Error("Active camera not set");
  19280. camera = this.activeCamera;
  19281. }
  19282. var cameraViewport = camera.viewport;
  19283. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19284. var identity = BABYLON.Matrix.Identity();
  19285. // Moving coordinates to local viewport world
  19286. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19287. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19288. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19289. };
  19290. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19291. if (!BABYLON.PickingInfo) {
  19292. return null;
  19293. }
  19294. var pickingInfo = null;
  19295. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19296. var mesh = this.meshes[meshIndex];
  19297. if (predicate) {
  19298. if (!predicate(mesh)) {
  19299. continue;
  19300. }
  19301. }
  19302. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19303. continue;
  19304. }
  19305. var world = mesh.getWorldMatrix();
  19306. var ray = rayFunction(world);
  19307. var result = mesh.intersects(ray, fastCheck);
  19308. if (!result || !result.hit)
  19309. continue;
  19310. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19311. continue;
  19312. pickingInfo = result;
  19313. if (fastCheck) {
  19314. break;
  19315. }
  19316. }
  19317. return pickingInfo || new BABYLON.PickingInfo();
  19318. };
  19319. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19320. if (!BABYLON.PickingInfo) {
  19321. return null;
  19322. }
  19323. var pickingInfos = new Array();
  19324. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19325. var mesh = this.meshes[meshIndex];
  19326. if (predicate) {
  19327. if (!predicate(mesh)) {
  19328. continue;
  19329. }
  19330. }
  19331. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19332. continue;
  19333. }
  19334. var world = mesh.getWorldMatrix();
  19335. var ray = rayFunction(world);
  19336. var result = mesh.intersects(ray, false);
  19337. if (!result || !result.hit)
  19338. continue;
  19339. pickingInfos.push(result);
  19340. }
  19341. return pickingInfos;
  19342. };
  19343. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19344. if (!BABYLON.PickingInfo) {
  19345. return null;
  19346. }
  19347. var pickingInfo = null;
  19348. camera = camera || this.activeCamera;
  19349. if (this.spriteManagers.length > 0) {
  19350. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19351. var spriteManager = this.spriteManagers[spriteIndex];
  19352. if (!spriteManager.isPickable) {
  19353. continue;
  19354. }
  19355. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19356. if (!result || !result.hit)
  19357. continue;
  19358. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19359. continue;
  19360. pickingInfo = result;
  19361. if (fastCheck) {
  19362. break;
  19363. }
  19364. }
  19365. }
  19366. return pickingInfo || new BABYLON.PickingInfo();
  19367. };
  19368. /** Launch a ray to try to pick a mesh in the scene
  19369. * @param x position on screen
  19370. * @param y position on screen
  19371. * @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
  19372. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19373. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19374. */
  19375. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19376. var _this = this;
  19377. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19378. };
  19379. /** Launch a ray to try to pick a sprite in the scene
  19380. * @param x position on screen
  19381. * @param y position on screen
  19382. * @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
  19383. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19384. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19385. */
  19386. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19387. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19388. };
  19389. /** Use the given ray to pick a mesh in the scene
  19390. * @param ray The ray to use to pick meshes
  19391. * @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
  19392. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19393. */
  19394. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19395. var _this = this;
  19396. return this._internalPick(function (world) {
  19397. if (!_this._pickWithRayInverseMatrix) {
  19398. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19399. }
  19400. world.invertToRef(_this._pickWithRayInverseMatrix);
  19401. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19402. }, predicate, fastCheck);
  19403. };
  19404. /**
  19405. * Launch a ray to try to pick a mesh in the scene
  19406. * @param x X position on screen
  19407. * @param y Y position on screen
  19408. * @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
  19409. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19410. */
  19411. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19412. var _this = this;
  19413. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19414. };
  19415. /**
  19416. * Launch a ray to try to pick a mesh in the scene
  19417. * @param ray Ray to use
  19418. * @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
  19419. */
  19420. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19421. var _this = this;
  19422. return this._internalMultiPick(function (world) {
  19423. if (!_this._pickWithRayInverseMatrix) {
  19424. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19425. }
  19426. world.invertToRef(_this._pickWithRayInverseMatrix);
  19427. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19428. }, predicate);
  19429. };
  19430. Scene.prototype.setPointerOverMesh = function (mesh) {
  19431. if (this._pointerOverMesh === mesh) {
  19432. return;
  19433. }
  19434. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19435. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19436. }
  19437. this._pointerOverMesh = mesh;
  19438. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19439. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19440. }
  19441. };
  19442. Scene.prototype.getPointerOverMesh = function () {
  19443. return this._pointerOverMesh;
  19444. };
  19445. Scene.prototype.setPointerOverSprite = function (sprite) {
  19446. if (this._pointerOverSprite === sprite) {
  19447. return;
  19448. }
  19449. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19450. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19451. }
  19452. this._pointerOverSprite = sprite;
  19453. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19454. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19455. }
  19456. };
  19457. Scene.prototype.getPointerOverSprite = function () {
  19458. return this._pointerOverSprite;
  19459. };
  19460. // Physics
  19461. Scene.prototype.getPhysicsEngine = function () {
  19462. return this._physicsEngine;
  19463. };
  19464. /**
  19465. * Enables physics to the current scene
  19466. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19467. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19468. * @return {boolean} was the physics engine initialized
  19469. */
  19470. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19471. if (this._physicsEngine) {
  19472. return true;
  19473. }
  19474. try {
  19475. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19476. return true;
  19477. }
  19478. catch (e) {
  19479. BABYLON.Tools.Error(e.message);
  19480. return false;
  19481. }
  19482. };
  19483. Scene.prototype.disablePhysicsEngine = function () {
  19484. if (!this._physicsEngine) {
  19485. return;
  19486. }
  19487. this._physicsEngine.dispose();
  19488. this._physicsEngine = undefined;
  19489. };
  19490. Scene.prototype.isPhysicsEnabled = function () {
  19491. return this._physicsEngine !== undefined;
  19492. };
  19493. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19494. var mesh = compound.parts[0].mesh;
  19495. mesh.physicsImpostor.dispose();
  19496. mesh.physicsImpostor = null;
  19497. };
  19498. // Misc.
  19499. Scene.prototype._rebuildGeometries = function () {
  19500. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19501. var geometry = _a[_i];
  19502. geometry._rebuild();
  19503. }
  19504. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19505. var mesh = _c[_b];
  19506. mesh._rebuild();
  19507. }
  19508. if (this.postProcessManager) {
  19509. this.postProcessManager._rebuild();
  19510. }
  19511. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19512. var layer = _e[_d];
  19513. layer._rebuild();
  19514. }
  19515. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19516. var highlightLayer = _g[_f];
  19517. highlightLayer._rebuild();
  19518. }
  19519. if (this._boundingBoxRenderer) {
  19520. this._boundingBoxRenderer._rebuild();
  19521. }
  19522. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  19523. var system = _j[_h];
  19524. system.rebuild();
  19525. }
  19526. if (this._postProcessRenderPipelineManager) {
  19527. this._postProcessRenderPipelineManager._rebuild();
  19528. }
  19529. };
  19530. Scene.prototype._rebuildTextures = function () {
  19531. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19532. var texture = _a[_i];
  19533. texture._rebuild();
  19534. }
  19535. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19536. };
  19537. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19538. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19539. if (replace === void 0) { replace = false; }
  19540. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19541. // Dispose existing camera or light in replace mode.
  19542. if (replace) {
  19543. if (this.activeCamera) {
  19544. this.activeCamera.dispose();
  19545. this.activeCamera = null;
  19546. }
  19547. if (this.lights) {
  19548. for (var i = 0; i < this.lights.length; i++) {
  19549. this.lights[i].dispose();
  19550. }
  19551. }
  19552. }
  19553. // Light
  19554. if (this.lights.length === 0) {
  19555. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19556. }
  19557. // Camera
  19558. if (!this.activeCamera) {
  19559. var worldExtends = this.getWorldExtends();
  19560. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19561. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19562. var camera;
  19563. var radius = worldSize.length() * 1.5;
  19564. if (createArcRotateCamera) {
  19565. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19566. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19567. arcRotateCamera.wheelPrecision = 100 / radius;
  19568. camera = arcRotateCamera;
  19569. }
  19570. else {
  19571. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19572. freeCamera.setTarget(worldCenter);
  19573. camera = freeCamera;
  19574. }
  19575. camera.minZ = radius * 0.01;
  19576. camera.maxZ = radius * 100;
  19577. camera.speed = radius * 0.2;
  19578. this.activeCamera = camera;
  19579. if (attachCameraControls) {
  19580. camera.attachControl(this.getEngine().getRenderingCanvas());
  19581. }
  19582. }
  19583. };
  19584. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19585. if (pbr === void 0) { pbr = false; }
  19586. if (scale === void 0) { scale = 1000; }
  19587. if (blur === void 0) { blur = 0; }
  19588. if (environmentTexture) {
  19589. this.environmentTexture = environmentTexture;
  19590. }
  19591. if (!this.environmentTexture) {
  19592. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19593. return;
  19594. }
  19595. // Skybox
  19596. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19597. if (pbr) {
  19598. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19599. hdrSkyboxMaterial.backFaceCulling = false;
  19600. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19601. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19602. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19603. hdrSkyboxMaterial.disableLighting = true;
  19604. hdrSkyboxMaterial.twoSidedLighting = true;
  19605. hdrSkybox.infiniteDistance = true;
  19606. hdrSkybox.material = hdrSkyboxMaterial;
  19607. }
  19608. else {
  19609. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19610. skyboxMaterial.backFaceCulling = false;
  19611. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19612. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19613. skyboxMaterial.disableLighting = true;
  19614. hdrSkybox.infiniteDistance = true;
  19615. hdrSkybox.material = skyboxMaterial;
  19616. }
  19617. return hdrSkybox;
  19618. };
  19619. Scene.prototype.createDefaultVRExperience = function () {
  19620. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19621. };
  19622. // Tags
  19623. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19624. if (tagsQuery === undefined) {
  19625. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19626. return list;
  19627. }
  19628. var listByTags = [];
  19629. forEach = forEach || (function (item) { return; });
  19630. for (var i in list) {
  19631. var item = list[i];
  19632. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19633. listByTags.push(item);
  19634. forEach(item);
  19635. }
  19636. }
  19637. return listByTags;
  19638. };
  19639. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19640. return this._getByTags(this.meshes, tagsQuery, forEach);
  19641. };
  19642. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19643. return this._getByTags(this.cameras, tagsQuery, forEach);
  19644. };
  19645. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19646. return this._getByTags(this.lights, tagsQuery, forEach);
  19647. };
  19648. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19649. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19650. };
  19651. /**
  19652. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19653. * This allowed control for front to back rendering or reversly depending of the special needs.
  19654. *
  19655. * @param renderingGroupId The rendering group id corresponding to its index
  19656. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19657. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19658. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19659. */
  19660. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19661. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19662. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19663. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19664. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19665. };
  19666. /**
  19667. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19668. *
  19669. * @param renderingGroupId The rendering group id corresponding to its index
  19670. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19671. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19672. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19673. */
  19674. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19675. if (depth === void 0) { depth = true; }
  19676. if (stencil === void 0) { stencil = true; }
  19677. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19678. };
  19679. /**
  19680. * Will flag all materials as dirty to trigger new shader compilation
  19681. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19682. */
  19683. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19684. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19685. var material = _a[_i];
  19686. if (predicate && !predicate(material)) {
  19687. continue;
  19688. }
  19689. material.markAsDirty(flag);
  19690. }
  19691. };
  19692. // Statics
  19693. Scene._FOGMODE_NONE = 0;
  19694. Scene._FOGMODE_EXP = 1;
  19695. Scene._FOGMODE_EXP2 = 2;
  19696. Scene._FOGMODE_LINEAR = 3;
  19697. Scene.MinDeltaTime = 1.0;
  19698. Scene.MaxDeltaTime = 1000.0;
  19699. /** The distance in pixel that you have to move to prevent some events */
  19700. Scene.DragMovementThreshold = 10; // in pixels
  19701. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19702. Scene.LongPressDelay = 500; // in milliseconds
  19703. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19704. Scene.DoubleClickDelay = 300; // in milliseconds
  19705. /** If you need to check double click without raising a single click at first click, enable this flag */
  19706. Scene.ExclusiveDoubleClickMode = false;
  19707. return Scene;
  19708. }());
  19709. BABYLON.Scene = Scene;
  19710. })(BABYLON || (BABYLON = {}));
  19711. //# sourceMappingURL=babylon.scene.js.map
  19712. var BABYLON;
  19713. (function (BABYLON) {
  19714. var Buffer = (function () {
  19715. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19716. if (engine instanceof BABYLON.Mesh) {
  19717. this._engine = engine.getScene().getEngine();
  19718. }
  19719. else {
  19720. this._engine = engine;
  19721. }
  19722. this._updatable = updatable;
  19723. this._data = data;
  19724. this._strideSize = stride;
  19725. if (!postponeInternalCreation) {
  19726. this.create();
  19727. }
  19728. this._instanced = instanced;
  19729. this._instanceDivisor = instanced ? 1 : 0;
  19730. }
  19731. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19732. // a lot of these parameters are ignored as they are overriden by the buffer
  19733. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19734. };
  19735. // Properties
  19736. Buffer.prototype.isUpdatable = function () {
  19737. return this._updatable;
  19738. };
  19739. Buffer.prototype.getData = function () {
  19740. return this._data;
  19741. };
  19742. Buffer.prototype.getBuffer = function () {
  19743. return this._buffer;
  19744. };
  19745. Buffer.prototype.getStrideSize = function () {
  19746. return this._strideSize;
  19747. };
  19748. Buffer.prototype.getIsInstanced = function () {
  19749. return this._instanced;
  19750. };
  19751. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19752. get: function () {
  19753. return this._instanceDivisor;
  19754. },
  19755. set: function (value) {
  19756. this._instanceDivisor = value;
  19757. if (value == 0) {
  19758. this._instanced = false;
  19759. }
  19760. else {
  19761. this._instanced = true;
  19762. }
  19763. },
  19764. enumerable: true,
  19765. configurable: true
  19766. });
  19767. // Methods
  19768. Buffer.prototype.create = function (data) {
  19769. if (!data && this._buffer) {
  19770. return; // nothing to do
  19771. }
  19772. data = data || this._data;
  19773. if (!this._buffer) {
  19774. if (this._updatable) {
  19775. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19776. this._data = data;
  19777. }
  19778. else {
  19779. this._buffer = this._engine.createVertexBuffer(data);
  19780. }
  19781. }
  19782. else if (this._updatable) {
  19783. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19784. this._data = data;
  19785. }
  19786. };
  19787. Buffer.prototype._rebuild = function () {
  19788. this._buffer = null;
  19789. this.create(this._data);
  19790. };
  19791. Buffer.prototype.update = function (data) {
  19792. this.create(data);
  19793. };
  19794. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19795. if (!this._buffer) {
  19796. return;
  19797. }
  19798. if (this._updatable) {
  19799. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19800. this._data = null;
  19801. }
  19802. };
  19803. Buffer.prototype.dispose = function () {
  19804. if (!this._buffer) {
  19805. return;
  19806. }
  19807. if (this._engine._releaseBuffer(this._buffer)) {
  19808. this._buffer = null;
  19809. }
  19810. };
  19811. return Buffer;
  19812. }());
  19813. BABYLON.Buffer = Buffer;
  19814. })(BABYLON || (BABYLON = {}));
  19815. //# sourceMappingURL=babylon.buffer.js.map
  19816. var BABYLON;
  19817. (function (BABYLON) {
  19818. var VertexBuffer = (function () {
  19819. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19820. if (!stride) {
  19821. // Deduce stride from kind
  19822. switch (kind) {
  19823. case VertexBuffer.PositionKind:
  19824. stride = 3;
  19825. break;
  19826. case VertexBuffer.NormalKind:
  19827. stride = 3;
  19828. break;
  19829. case VertexBuffer.UVKind:
  19830. case VertexBuffer.UV2Kind:
  19831. case VertexBuffer.UV3Kind:
  19832. case VertexBuffer.UV4Kind:
  19833. case VertexBuffer.UV5Kind:
  19834. case VertexBuffer.UV6Kind:
  19835. stride = 2;
  19836. break;
  19837. case VertexBuffer.TangentKind:
  19838. case VertexBuffer.ColorKind:
  19839. stride = 4;
  19840. break;
  19841. case VertexBuffer.MatricesIndicesKind:
  19842. case VertexBuffer.MatricesIndicesExtraKind:
  19843. stride = 4;
  19844. break;
  19845. case VertexBuffer.MatricesWeightsKind:
  19846. case VertexBuffer.MatricesWeightsExtraKind:
  19847. stride = 4;
  19848. break;
  19849. }
  19850. }
  19851. if (data instanceof BABYLON.Buffer) {
  19852. if (!stride) {
  19853. stride = data.getStrideSize();
  19854. }
  19855. this._buffer = data;
  19856. this._ownsBuffer = false;
  19857. }
  19858. else {
  19859. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19860. this._ownsBuffer = true;
  19861. }
  19862. this._stride = stride;
  19863. this._offset = offset ? offset : 0;
  19864. this._size = size ? size : stride;
  19865. this._kind = kind;
  19866. }
  19867. VertexBuffer.prototype._rebuild = function () {
  19868. if (!this._buffer) {
  19869. return;
  19870. }
  19871. this._buffer._rebuild();
  19872. };
  19873. /**
  19874. * Returns the kind of the VertexBuffer (string).
  19875. */
  19876. VertexBuffer.prototype.getKind = function () {
  19877. return this._kind;
  19878. };
  19879. // Properties
  19880. /**
  19881. * Boolean : is the VertexBuffer updatable ?
  19882. */
  19883. VertexBuffer.prototype.isUpdatable = function () {
  19884. return this._buffer.isUpdatable();
  19885. };
  19886. /**
  19887. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  19888. */
  19889. VertexBuffer.prototype.getData = function () {
  19890. return this._buffer.getData();
  19891. };
  19892. /**
  19893. * Returns the WebGLBuffer associated to the VertexBuffer.
  19894. */
  19895. VertexBuffer.prototype.getBuffer = function () {
  19896. return this._buffer.getBuffer();
  19897. };
  19898. /**
  19899. * Returns the stride of the VertexBuffer (integer).
  19900. */
  19901. VertexBuffer.prototype.getStrideSize = function () {
  19902. return this._stride;
  19903. };
  19904. /**
  19905. * Returns the offset (integer).
  19906. */
  19907. VertexBuffer.prototype.getOffset = function () {
  19908. return this._offset;
  19909. };
  19910. /**
  19911. * Returns the VertexBuffer total size (integer).
  19912. */
  19913. VertexBuffer.prototype.getSize = function () {
  19914. return this._size;
  19915. };
  19916. /**
  19917. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  19918. */
  19919. VertexBuffer.prototype.getIsInstanced = function () {
  19920. return this._buffer.getIsInstanced();
  19921. };
  19922. /**
  19923. * Returns the instancing divisor, zero for non-instanced (integer).
  19924. */
  19925. VertexBuffer.prototype.getInstanceDivisor = function () {
  19926. return this._buffer.instanceDivisor;
  19927. };
  19928. // Methods
  19929. /**
  19930. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  19931. * Returns the created WebGLBuffer.
  19932. */
  19933. VertexBuffer.prototype.create = function (data) {
  19934. return this._buffer.create(data);
  19935. };
  19936. /**
  19937. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19938. * Returns the updated WebGLBuffer.
  19939. */
  19940. VertexBuffer.prototype.update = function (data) {
  19941. return this._buffer.update(data);
  19942. };
  19943. /**
  19944. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19945. * Returns the directly updated WebGLBuffer.
  19946. */
  19947. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19948. return this._buffer.updateDirectly(data, offset);
  19949. };
  19950. /**
  19951. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  19952. */
  19953. VertexBuffer.prototype.dispose = function () {
  19954. if (this._ownsBuffer) {
  19955. this._buffer.dispose();
  19956. }
  19957. };
  19958. Object.defineProperty(VertexBuffer, "PositionKind", {
  19959. get: function () {
  19960. return VertexBuffer._PositionKind;
  19961. },
  19962. enumerable: true,
  19963. configurable: true
  19964. });
  19965. Object.defineProperty(VertexBuffer, "NormalKind", {
  19966. get: function () {
  19967. return VertexBuffer._NormalKind;
  19968. },
  19969. enumerable: true,
  19970. configurable: true
  19971. });
  19972. Object.defineProperty(VertexBuffer, "TangentKind", {
  19973. get: function () {
  19974. return VertexBuffer._TangentKind;
  19975. },
  19976. enumerable: true,
  19977. configurable: true
  19978. });
  19979. Object.defineProperty(VertexBuffer, "UVKind", {
  19980. get: function () {
  19981. return VertexBuffer._UVKind;
  19982. },
  19983. enumerable: true,
  19984. configurable: true
  19985. });
  19986. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19987. get: function () {
  19988. return VertexBuffer._UV2Kind;
  19989. },
  19990. enumerable: true,
  19991. configurable: true
  19992. });
  19993. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19994. get: function () {
  19995. return VertexBuffer._UV3Kind;
  19996. },
  19997. enumerable: true,
  19998. configurable: true
  19999. });
  20000. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20001. get: function () {
  20002. return VertexBuffer._UV4Kind;
  20003. },
  20004. enumerable: true,
  20005. configurable: true
  20006. });
  20007. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20008. get: function () {
  20009. return VertexBuffer._UV5Kind;
  20010. },
  20011. enumerable: true,
  20012. configurable: true
  20013. });
  20014. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20015. get: function () {
  20016. return VertexBuffer._UV6Kind;
  20017. },
  20018. enumerable: true,
  20019. configurable: true
  20020. });
  20021. Object.defineProperty(VertexBuffer, "ColorKind", {
  20022. get: function () {
  20023. return VertexBuffer._ColorKind;
  20024. },
  20025. enumerable: true,
  20026. configurable: true
  20027. });
  20028. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20029. get: function () {
  20030. return VertexBuffer._MatricesIndicesKind;
  20031. },
  20032. enumerable: true,
  20033. configurable: true
  20034. });
  20035. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20036. get: function () {
  20037. return VertexBuffer._MatricesWeightsKind;
  20038. },
  20039. enumerable: true,
  20040. configurable: true
  20041. });
  20042. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20043. get: function () {
  20044. return VertexBuffer._MatricesIndicesExtraKind;
  20045. },
  20046. enumerable: true,
  20047. configurable: true
  20048. });
  20049. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20050. get: function () {
  20051. return VertexBuffer._MatricesWeightsExtraKind;
  20052. },
  20053. enumerable: true,
  20054. configurable: true
  20055. });
  20056. // Enums
  20057. VertexBuffer._PositionKind = "position";
  20058. VertexBuffer._NormalKind = "normal";
  20059. VertexBuffer._TangentKind = "tangent";
  20060. VertexBuffer._UVKind = "uv";
  20061. VertexBuffer._UV2Kind = "uv2";
  20062. VertexBuffer._UV3Kind = "uv3";
  20063. VertexBuffer._UV4Kind = "uv4";
  20064. VertexBuffer._UV5Kind = "uv5";
  20065. VertexBuffer._UV6Kind = "uv6";
  20066. VertexBuffer._ColorKind = "color";
  20067. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20068. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20069. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20070. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20071. return VertexBuffer;
  20072. }());
  20073. BABYLON.VertexBuffer = VertexBuffer;
  20074. })(BABYLON || (BABYLON = {}));
  20075. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20076. var BABYLON;
  20077. (function (BABYLON) {
  20078. var InternalTexture = (function () {
  20079. function InternalTexture(engine, dataSource) {
  20080. this.onLoadedObservable = new BABYLON.Observable();
  20081. // Private
  20082. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  20083. this._references = 1;
  20084. this._engine = engine;
  20085. this._dataSource = dataSource;
  20086. this._webGLTexture = engine._createTexture();
  20087. }
  20088. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  20089. get: function () {
  20090. return this._dataSource;
  20091. },
  20092. enumerable: true,
  20093. configurable: true
  20094. });
  20095. InternalTexture.prototype.incrementReferences = function () {
  20096. this._references++;
  20097. };
  20098. InternalTexture.prototype.updateSize = function (width, height) {
  20099. this.width = width;
  20100. this.height = height;
  20101. this._size = width * height;
  20102. this.baseWidth = width;
  20103. this.baseHeight = height;
  20104. };
  20105. InternalTexture.prototype._rebuild = function () {
  20106. var _this = this;
  20107. var proxy;
  20108. this.isReady = false;
  20109. this._cachedCoordinatesMode = null;
  20110. this._cachedWrapU = null;
  20111. this._cachedWrapV = null;
  20112. this._cachedAnisotropicFilteringLevel = null;
  20113. switch (this._dataSource) {
  20114. case InternalTexture.DATASOURCE_TEMP:
  20115. return;
  20116. case InternalTexture.DATASOURCE_URL:
  20117. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  20118. _this.isReady = true;
  20119. }, null, this._buffer, null, this.format);
  20120. proxy._swapAndDie(this);
  20121. return;
  20122. case InternalTexture.DATASOURCE_RAW:
  20123. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20124. proxy._swapAndDie(this);
  20125. this.isReady = true;
  20126. return;
  20127. case InternalTexture.DATASOURCE_DYNAMIC:
  20128. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  20129. proxy._swapAndDie(this);
  20130. // The engine will make sure to update content so no need to flag it as isReady = true
  20131. return;
  20132. case InternalTexture.DATASOURCE_RENDERTARGET:
  20133. var options = new BABYLON.RenderTargetCreationOptions();
  20134. options.generateDepthBuffer = this._generateDepthBuffer;
  20135. options.generateMipMaps = this.generateMipMaps;
  20136. options.generateStencilBuffer = this._generateStencilBuffer;
  20137. options.samplingMode = this.samplingMode;
  20138. options.type = this.type;
  20139. if (this.isCube) {
  20140. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20141. }
  20142. else {
  20143. var size = {
  20144. width: this.width,
  20145. height: this.height
  20146. };
  20147. proxy = this._engine.createRenderTargetTexture(size, options);
  20148. }
  20149. proxy._swapAndDie(this);
  20150. this.isReady = true;
  20151. return;
  20152. case InternalTexture.DATASOURCE_CUBE:
  20153. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20154. _this.isReady = true;
  20155. }, null, this.format, this._extension);
  20156. proxy._swapAndDie(this);
  20157. return;
  20158. case InternalTexture.DATASOURCE_CUBERAW:
  20159. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20160. proxy._swapAndDie(this);
  20161. this.isReady = true;
  20162. return;
  20163. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20164. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20165. proxy._swapAndDie(_this);
  20166. _this.isReady = true;
  20167. }, null, this.format, this._extension);
  20168. return;
  20169. }
  20170. };
  20171. InternalTexture.prototype._swapAndDie = function (target) {
  20172. target._webGLTexture = this._webGLTexture;
  20173. if (this._framebuffer) {
  20174. target._framebuffer = this._framebuffer;
  20175. }
  20176. if (this._depthStencilBuffer) {
  20177. target._depthStencilBuffer = this._depthStencilBuffer;
  20178. }
  20179. if (this._lodTextureHigh) {
  20180. if (target._lodTextureHigh) {
  20181. target._lodTextureHigh.dispose();
  20182. }
  20183. target._lodTextureHigh = this._lodTextureHigh;
  20184. }
  20185. if (this._lodTextureMid) {
  20186. if (target._lodTextureMid) {
  20187. target._lodTextureMid.dispose();
  20188. }
  20189. target._lodTextureMid = this._lodTextureMid;
  20190. }
  20191. if (this._lodTextureLow) {
  20192. if (target._lodTextureLow) {
  20193. target._lodTextureLow.dispose();
  20194. }
  20195. target._lodTextureLow = this._lodTextureLow;
  20196. }
  20197. var cache = this._engine.getLoadedTexturesCache();
  20198. var index = cache.indexOf(this);
  20199. if (index !== -1) {
  20200. cache.splice(index, 1);
  20201. }
  20202. };
  20203. InternalTexture.prototype.dispose = function () {
  20204. if (!this._webGLTexture) {
  20205. return;
  20206. }
  20207. this._references--;
  20208. if (this._references === 0) {
  20209. this._engine._releaseTexture(this);
  20210. this._webGLTexture = null;
  20211. }
  20212. };
  20213. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20214. InternalTexture.DATASOURCE_URL = 1;
  20215. InternalTexture.DATASOURCE_TEMP = 2;
  20216. InternalTexture.DATASOURCE_RAW = 3;
  20217. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20218. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20219. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20220. InternalTexture.DATASOURCE_CUBE = 7;
  20221. InternalTexture.DATASOURCE_CUBERAW = 8;
  20222. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20223. return InternalTexture;
  20224. }());
  20225. BABYLON.InternalTexture = InternalTexture;
  20226. })(BABYLON || (BABYLON = {}));
  20227. //# sourceMappingURL=babylon.internalTexture.js.map
  20228. var BABYLON;
  20229. (function (BABYLON) {
  20230. var BaseTexture = (function () {
  20231. function BaseTexture(scene) {
  20232. this._hasAlpha = false;
  20233. this.getAlphaFromRGB = false;
  20234. this.level = 1;
  20235. this.coordinatesIndex = 0;
  20236. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20237. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20238. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20239. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20240. this.isCube = false;
  20241. this.gammaSpace = true;
  20242. this.invertZ = false;
  20243. this.lodLevelInAlpha = false;
  20244. this.lodGenerationOffset = 0.0;
  20245. this.lodGenerationScale = 0.8;
  20246. this.isRenderTarget = false;
  20247. this.animations = new Array();
  20248. /**
  20249. * An event triggered when the texture is disposed.
  20250. * @type {BABYLON.Observable}
  20251. */
  20252. this.onDisposeObservable = new BABYLON.Observable();
  20253. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20254. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20255. this._scene.textures.push(this);
  20256. this._uid = null;
  20257. }
  20258. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20259. get: function () {
  20260. return this._hasAlpha;
  20261. },
  20262. set: function (value) {
  20263. if (this._hasAlpha === value) {
  20264. return;
  20265. }
  20266. this._hasAlpha = value;
  20267. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20268. },
  20269. enumerable: true,
  20270. configurable: true
  20271. });
  20272. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20273. get: function () {
  20274. return this._coordinatesMode;
  20275. },
  20276. set: function (value) {
  20277. if (this._coordinatesMode === value) {
  20278. return;
  20279. }
  20280. this._coordinatesMode = value;
  20281. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20282. },
  20283. enumerable: true,
  20284. configurable: true
  20285. });
  20286. Object.defineProperty(BaseTexture.prototype, "uid", {
  20287. get: function () {
  20288. if (!this._uid) {
  20289. this._uid = BABYLON.Tools.RandomId();
  20290. }
  20291. return this._uid;
  20292. },
  20293. enumerable: true,
  20294. configurable: true
  20295. });
  20296. BaseTexture.prototype.toString = function () {
  20297. return this.name;
  20298. };
  20299. BaseTexture.prototype.getClassName = function () {
  20300. return "BaseTexture";
  20301. };
  20302. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20303. set: function (callback) {
  20304. if (this._onDisposeObserver) {
  20305. this.onDisposeObservable.remove(this._onDisposeObserver);
  20306. }
  20307. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20308. },
  20309. enumerable: true,
  20310. configurable: true
  20311. });
  20312. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20313. get: function () {
  20314. return true;
  20315. },
  20316. enumerable: true,
  20317. configurable: true
  20318. });
  20319. BaseTexture.prototype.getScene = function () {
  20320. return this._scene;
  20321. };
  20322. BaseTexture.prototype.getTextureMatrix = function () {
  20323. return null;
  20324. };
  20325. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20326. return null;
  20327. };
  20328. BaseTexture.prototype.getInternalTexture = function () {
  20329. return this._texture;
  20330. };
  20331. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20332. return !this.isBlocking || this.isReady();
  20333. };
  20334. BaseTexture.prototype.isReady = function () {
  20335. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20336. this.delayLoad();
  20337. return false;
  20338. }
  20339. if (this._texture) {
  20340. return this._texture.isReady;
  20341. }
  20342. return false;
  20343. };
  20344. BaseTexture.prototype.getSize = function () {
  20345. if (this._texture.width) {
  20346. return new BABYLON.Size(this._texture.width, this._texture.height);
  20347. }
  20348. if (this._texture._size) {
  20349. return new BABYLON.Size(this._texture._size, this._texture._size);
  20350. }
  20351. return BABYLON.Size.Zero();
  20352. };
  20353. BaseTexture.prototype.getBaseSize = function () {
  20354. if (!this.isReady() || !this._texture)
  20355. return BABYLON.Size.Zero();
  20356. if (this._texture._size) {
  20357. return new BABYLON.Size(this._texture._size, this._texture._size);
  20358. }
  20359. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20360. };
  20361. BaseTexture.prototype.scale = function (ratio) {
  20362. };
  20363. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20364. get: function () {
  20365. return false;
  20366. },
  20367. enumerable: true,
  20368. configurable: true
  20369. });
  20370. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20371. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20372. for (var index = 0; index < texturesCache.length; index++) {
  20373. var texturesCacheEntry = texturesCache[index];
  20374. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20375. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20376. texturesCacheEntry.incrementReferences();
  20377. return texturesCacheEntry;
  20378. }
  20379. }
  20380. }
  20381. return null;
  20382. };
  20383. BaseTexture.prototype._rebuild = function () {
  20384. };
  20385. BaseTexture.prototype.delayLoad = function () {
  20386. };
  20387. BaseTexture.prototype.clone = function () {
  20388. return null;
  20389. };
  20390. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20391. get: function () {
  20392. if (!this._texture) {
  20393. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20394. }
  20395. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20396. },
  20397. enumerable: true,
  20398. configurable: true
  20399. });
  20400. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20401. get: function () {
  20402. if (!this._texture) {
  20403. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20404. }
  20405. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20406. },
  20407. enumerable: true,
  20408. configurable: true
  20409. });
  20410. BaseTexture.prototype.readPixels = function (faceIndex) {
  20411. if (faceIndex === void 0) { faceIndex = 0; }
  20412. if (!this._texture) {
  20413. return null;
  20414. }
  20415. var size = this.getSize();
  20416. var engine = this.getScene().getEngine();
  20417. if (this._texture.isCube) {
  20418. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20419. }
  20420. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20421. };
  20422. BaseTexture.prototype.releaseInternalTexture = function () {
  20423. if (this._texture) {
  20424. this._texture.dispose();
  20425. this._texture = null;
  20426. }
  20427. };
  20428. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20429. get: function () {
  20430. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20431. return null;
  20432. }
  20433. if (!this._texture._sphericalPolynomial) {
  20434. this._texture._sphericalPolynomial =
  20435. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20436. }
  20437. return this._texture._sphericalPolynomial;
  20438. },
  20439. set: function (value) {
  20440. if (this._texture) {
  20441. this._texture._sphericalPolynomial = value;
  20442. }
  20443. },
  20444. enumerable: true,
  20445. configurable: true
  20446. });
  20447. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20448. get: function () {
  20449. if (this._texture) {
  20450. return this._texture._lodTextureHigh;
  20451. }
  20452. return null;
  20453. },
  20454. enumerable: true,
  20455. configurable: true
  20456. });
  20457. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20458. get: function () {
  20459. if (this._texture) {
  20460. return this._texture._lodTextureMid;
  20461. }
  20462. return null;
  20463. },
  20464. enumerable: true,
  20465. configurable: true
  20466. });
  20467. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20468. get: function () {
  20469. if (this._texture) {
  20470. return this._texture._lodTextureLow;
  20471. }
  20472. return null;
  20473. },
  20474. enumerable: true,
  20475. configurable: true
  20476. });
  20477. BaseTexture.prototype.dispose = function () {
  20478. // Animations
  20479. this.getScene().stopAnimation(this);
  20480. // Remove from scene
  20481. this._scene._removePendingData(this);
  20482. var index = this._scene.textures.indexOf(this);
  20483. if (index >= 0) {
  20484. this._scene.textures.splice(index, 1);
  20485. }
  20486. if (this._texture === undefined) {
  20487. return;
  20488. }
  20489. // Release
  20490. this.releaseInternalTexture();
  20491. // Callback
  20492. this.onDisposeObservable.notifyObservers(this);
  20493. this.onDisposeObservable.clear();
  20494. };
  20495. BaseTexture.prototype.serialize = function () {
  20496. if (!this.name) {
  20497. return null;
  20498. }
  20499. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20500. // Animations
  20501. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20502. return serializationObject;
  20503. };
  20504. BaseTexture.WhenAllReady = function (textures, callback) {
  20505. var numRemaining = textures.length;
  20506. if (numRemaining === 0) {
  20507. callback();
  20508. return;
  20509. }
  20510. var _loop_1 = function () {
  20511. texture = textures[i];
  20512. if (texture.isReady()) {
  20513. if (--numRemaining === 0) {
  20514. callback();
  20515. }
  20516. }
  20517. else {
  20518. onLoadObservable = texture.onLoadObservable;
  20519. var onLoadCallback_1 = function () {
  20520. onLoadObservable.removeCallback(onLoadCallback_1);
  20521. if (--numRemaining === 0) {
  20522. callback();
  20523. }
  20524. };
  20525. onLoadObservable.add(onLoadCallback_1);
  20526. }
  20527. };
  20528. var texture, onLoadObservable;
  20529. for (var i = 0; i < textures.length; i++) {
  20530. _loop_1();
  20531. }
  20532. };
  20533. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20534. __decorate([
  20535. BABYLON.serialize()
  20536. ], BaseTexture.prototype, "name", void 0);
  20537. __decorate([
  20538. BABYLON.serialize("hasAlpha")
  20539. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20540. __decorate([
  20541. BABYLON.serialize()
  20542. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20543. __decorate([
  20544. BABYLON.serialize()
  20545. ], BaseTexture.prototype, "level", void 0);
  20546. __decorate([
  20547. BABYLON.serialize()
  20548. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20549. __decorate([
  20550. BABYLON.serialize("coordinatesMode")
  20551. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20552. __decorate([
  20553. BABYLON.serialize()
  20554. ], BaseTexture.prototype, "wrapU", void 0);
  20555. __decorate([
  20556. BABYLON.serialize()
  20557. ], BaseTexture.prototype, "wrapV", void 0);
  20558. __decorate([
  20559. BABYLON.serialize()
  20560. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20561. __decorate([
  20562. BABYLON.serialize()
  20563. ], BaseTexture.prototype, "isCube", void 0);
  20564. __decorate([
  20565. BABYLON.serialize()
  20566. ], BaseTexture.prototype, "gammaSpace", void 0);
  20567. __decorate([
  20568. BABYLON.serialize()
  20569. ], BaseTexture.prototype, "invertZ", void 0);
  20570. __decorate([
  20571. BABYLON.serialize()
  20572. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20573. __decorate([
  20574. BABYLON.serialize()
  20575. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20576. __decorate([
  20577. BABYLON.serialize()
  20578. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20579. __decorate([
  20580. BABYLON.serialize()
  20581. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20582. return BaseTexture;
  20583. }());
  20584. BABYLON.BaseTexture = BaseTexture;
  20585. })(BABYLON || (BABYLON = {}));
  20586. //# sourceMappingURL=babylon.baseTexture.js.map
  20587. var BABYLON;
  20588. (function (BABYLON) {
  20589. var Texture = (function (_super) {
  20590. __extends(Texture, _super);
  20591. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20592. if (noMipmap === void 0) { noMipmap = false; }
  20593. if (invertY === void 0) { invertY = true; }
  20594. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20595. if (onLoad === void 0) { onLoad = null; }
  20596. if (onError === void 0) { onError = null; }
  20597. if (buffer === void 0) { buffer = null; }
  20598. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20599. var _this = _super.call(this, scene) || this;
  20600. _this.uOffset = 0;
  20601. _this.vOffset = 0;
  20602. _this.uScale = 1.0;
  20603. _this.vScale = 1.0;
  20604. _this.uAng = 0;
  20605. _this.vAng = 0;
  20606. _this.wAng = 0;
  20607. _this._isBlocking = true;
  20608. _this.name = url;
  20609. _this.url = url;
  20610. _this._noMipmap = noMipmap;
  20611. _this._invertY = invertY;
  20612. _this._samplingMode = samplingMode;
  20613. _this._buffer = buffer;
  20614. _this._deleteBuffer = deleteBuffer;
  20615. _this._format = format;
  20616. scene = _this.getScene();
  20617. var load = function () {
  20618. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20619. _this.onLoadObservable.notifyObservers(_this);
  20620. }
  20621. if (onLoad) {
  20622. onLoad();
  20623. }
  20624. if (!_this.isBlocking) {
  20625. scene.resetCachedMaterial();
  20626. }
  20627. };
  20628. if (!url) {
  20629. _this._delayedOnLoad = load;
  20630. _this._delayedOnError = onError;
  20631. return _this;
  20632. }
  20633. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  20634. if (!_this._texture) {
  20635. if (!scene.useDelayedTextureLoading) {
  20636. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20637. if (deleteBuffer) {
  20638. delete _this._buffer;
  20639. }
  20640. }
  20641. else {
  20642. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20643. _this._delayedOnLoad = load;
  20644. _this._delayedOnError = onError;
  20645. }
  20646. }
  20647. else {
  20648. if (_this._texture.isReady) {
  20649. BABYLON.Tools.SetImmediate(function () { return load(); });
  20650. }
  20651. else {
  20652. _this._texture.onLoadedObservable.add(load);
  20653. }
  20654. }
  20655. return _this;
  20656. }
  20657. Object.defineProperty(Texture.prototype, "noMipmap", {
  20658. get: function () {
  20659. return this._noMipmap;
  20660. },
  20661. enumerable: true,
  20662. configurable: true
  20663. });
  20664. Object.defineProperty(Texture.prototype, "isBlocking", {
  20665. get: function () {
  20666. return this._isBlocking;
  20667. },
  20668. set: function (value) {
  20669. this._isBlocking = value;
  20670. },
  20671. enumerable: true,
  20672. configurable: true
  20673. });
  20674. Object.defineProperty(Texture.prototype, "samplingMode", {
  20675. get: function () {
  20676. return this._samplingMode;
  20677. },
  20678. enumerable: true,
  20679. configurable: true
  20680. });
  20681. Texture.prototype.updateURL = function (url) {
  20682. this.url = url;
  20683. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20684. this.delayLoad();
  20685. };
  20686. Texture.prototype.delayLoad = function () {
  20687. var _this = this;
  20688. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20689. return;
  20690. }
  20691. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20692. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20693. if (!this._texture) {
  20694. 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);
  20695. if (this._deleteBuffer) {
  20696. delete this._buffer;
  20697. }
  20698. }
  20699. else {
  20700. if (this._texture.isReady) {
  20701. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20702. }
  20703. else {
  20704. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  20705. }
  20706. }
  20707. };
  20708. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20709. if (!this._texture) {
  20710. return;
  20711. }
  20712. this._samplingMode = samplingMode;
  20713. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20714. };
  20715. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20716. x *= this.uScale;
  20717. y *= this.vScale;
  20718. x -= 0.5 * this.uScale;
  20719. y -= 0.5 * this.vScale;
  20720. z -= 0.5;
  20721. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20722. t.x += 0.5 * this.uScale + this.uOffset;
  20723. t.y += 0.5 * this.vScale + this.vOffset;
  20724. t.z += 0.5;
  20725. };
  20726. Texture.prototype.getTextureMatrix = function () {
  20727. var _this = this;
  20728. if (this.uOffset === this._cachedUOffset &&
  20729. this.vOffset === this._cachedVOffset &&
  20730. this.uScale === this._cachedUScale &&
  20731. this.vScale === this._cachedVScale &&
  20732. this.uAng === this._cachedUAng &&
  20733. this.vAng === this._cachedVAng &&
  20734. this.wAng === this._cachedWAng) {
  20735. return this._cachedTextureMatrix;
  20736. }
  20737. this._cachedUOffset = this.uOffset;
  20738. this._cachedVOffset = this.vOffset;
  20739. this._cachedUScale = this.uScale;
  20740. this._cachedVScale = this.vScale;
  20741. this._cachedUAng = this.uAng;
  20742. this._cachedVAng = this.vAng;
  20743. this._cachedWAng = this.wAng;
  20744. if (!this._cachedTextureMatrix) {
  20745. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20746. this._rowGenerationMatrix = new BABYLON.Matrix();
  20747. this._t0 = BABYLON.Vector3.Zero();
  20748. this._t1 = BABYLON.Vector3.Zero();
  20749. this._t2 = BABYLON.Vector3.Zero();
  20750. }
  20751. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20752. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20753. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20754. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20755. this._t1.subtractInPlace(this._t0);
  20756. this._t2.subtractInPlace(this._t0);
  20757. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20758. this._cachedTextureMatrix.m[0] = this._t1.x;
  20759. this._cachedTextureMatrix.m[1] = this._t1.y;
  20760. this._cachedTextureMatrix.m[2] = this._t1.z;
  20761. this._cachedTextureMatrix.m[4] = this._t2.x;
  20762. this._cachedTextureMatrix.m[5] = this._t2.y;
  20763. this._cachedTextureMatrix.m[6] = this._t2.z;
  20764. this._cachedTextureMatrix.m[8] = this._t0.x;
  20765. this._cachedTextureMatrix.m[9] = this._t0.y;
  20766. this._cachedTextureMatrix.m[10] = this._t0.z;
  20767. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20768. return mat.hasTexture(_this);
  20769. });
  20770. return this._cachedTextureMatrix;
  20771. };
  20772. Texture.prototype.getReflectionTextureMatrix = function () {
  20773. var _this = this;
  20774. var scene = this.getScene();
  20775. if (this.uOffset === this._cachedUOffset &&
  20776. this.vOffset === this._cachedVOffset &&
  20777. this.uScale === this._cachedUScale &&
  20778. this.vScale === this._cachedVScale &&
  20779. this.coordinatesMode === this._cachedCoordinatesMode) {
  20780. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  20781. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  20782. return this._cachedTextureMatrix;
  20783. }
  20784. }
  20785. else {
  20786. return this._cachedTextureMatrix;
  20787. }
  20788. }
  20789. if (!this._cachedTextureMatrix) {
  20790. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20791. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20792. }
  20793. this._cachedUOffset = this.uOffset;
  20794. this._cachedVOffset = this.vOffset;
  20795. this._cachedUScale = this.uScale;
  20796. this._cachedVScale = this.vScale;
  20797. this._cachedCoordinatesMode = this.coordinatesMode;
  20798. switch (this.coordinatesMode) {
  20799. case Texture.PLANAR_MODE:
  20800. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20801. this._cachedTextureMatrix[0] = this.uScale;
  20802. this._cachedTextureMatrix[5] = this.vScale;
  20803. this._cachedTextureMatrix[12] = this.uOffset;
  20804. this._cachedTextureMatrix[13] = this.vOffset;
  20805. break;
  20806. case Texture.PROJECTION_MODE:
  20807. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20808. this._projectionModeMatrix.m[0] = 0.5;
  20809. this._projectionModeMatrix.m[5] = -0.5;
  20810. this._projectionModeMatrix.m[10] = 0.0;
  20811. this._projectionModeMatrix.m[12] = 0.5;
  20812. this._projectionModeMatrix.m[13] = 0.5;
  20813. this._projectionModeMatrix.m[14] = 1.0;
  20814. this._projectionModeMatrix.m[15] = 1.0;
  20815. var projectionMatrix = scene.getProjectionMatrix();
  20816. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  20817. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20818. break;
  20819. default:
  20820. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20821. break;
  20822. }
  20823. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20824. return (mat.getActiveTextures().indexOf(_this) !== -1);
  20825. });
  20826. return this._cachedTextureMatrix;
  20827. };
  20828. Texture.prototype.clone = function () {
  20829. var _this = this;
  20830. return BABYLON.SerializationHelper.Clone(function () {
  20831. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20832. }, this);
  20833. };
  20834. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  20835. get: function () {
  20836. if (!this._onLoadObservable) {
  20837. this._onLoadObservable = new BABYLON.Observable();
  20838. }
  20839. return this._onLoadObservable;
  20840. },
  20841. enumerable: true,
  20842. configurable: true
  20843. });
  20844. Texture.prototype.serialize = function () {
  20845. var serializationObject = _super.prototype.serialize.call(this);
  20846. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  20847. serializationObject.base64String = this._buffer;
  20848. serializationObject.name = serializationObject.name.replace("data:", "");
  20849. }
  20850. return serializationObject;
  20851. };
  20852. Texture.prototype.getClassName = function () {
  20853. return "Texture";
  20854. };
  20855. Texture.prototype.dispose = function () {
  20856. _super.prototype.dispose.call(this);
  20857. if (this.onLoadObservable) {
  20858. this.onLoadObservable.clear();
  20859. this._onLoadObservable = null;
  20860. }
  20861. this._delayedOnLoad = null;
  20862. this._delayedOnError = null;
  20863. };
  20864. // Statics
  20865. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20866. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20867. if (onLoad === void 0) { onLoad = null; }
  20868. if (onError === void 0) { onError = null; }
  20869. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20870. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  20871. };
  20872. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20873. if (parsedTexture.customType) {
  20874. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  20875. // Update Sampling Mode
  20876. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  20877. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  20878. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  20879. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  20880. }
  20881. }
  20882. return parsedCustomTexture;
  20883. }
  20884. if (parsedTexture.isCube) {
  20885. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20886. }
  20887. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20888. return null;
  20889. }
  20890. var texture = BABYLON.SerializationHelper.Parse(function () {
  20891. if (parsedTexture.mirrorPlane) {
  20892. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20893. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20894. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20895. return mirrorTexture;
  20896. }
  20897. else if (parsedTexture.isRenderTarget) {
  20898. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20899. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20900. return renderTargetTexture;
  20901. }
  20902. else {
  20903. var texture;
  20904. if (parsedTexture.base64String) {
  20905. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20906. }
  20907. else {
  20908. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20909. }
  20910. return texture;
  20911. }
  20912. }, parsedTexture, scene);
  20913. // Update Sampling Mode
  20914. if (parsedTexture.samplingMode) {
  20915. var sampling = parsedTexture.samplingMode;
  20916. if (texture._samplingMode !== sampling) {
  20917. texture.updateSamplingMode(sampling);
  20918. }
  20919. }
  20920. // Animations
  20921. if (parsedTexture.animations) {
  20922. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20923. var parsedAnimation = parsedTexture.animations[animationIndex];
  20924. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20925. }
  20926. }
  20927. return texture;
  20928. };
  20929. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20930. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20931. if (noMipmap === void 0) { noMipmap = false; }
  20932. if (invertY === void 0) { invertY = true; }
  20933. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20934. if (onLoad === void 0) { onLoad = null; }
  20935. if (onError === void 0) { onError = null; }
  20936. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20937. if (name.substr(0, 5) !== "data:") {
  20938. name = "data:" + name;
  20939. }
  20940. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  20941. };
  20942. // Constants
  20943. Texture.NEAREST_SAMPLINGMODE = 1;
  20944. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  20945. Texture.BILINEAR_SAMPLINGMODE = 2;
  20946. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  20947. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20948. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  20949. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  20950. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  20951. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  20952. Texture.NEAREST_LINEAR = 7;
  20953. Texture.NEAREST_NEAREST = 8;
  20954. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  20955. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  20956. Texture.LINEAR_LINEAR = 11;
  20957. Texture.LINEAR_NEAREST = 12;
  20958. Texture.EXPLICIT_MODE = 0;
  20959. Texture.SPHERICAL_MODE = 1;
  20960. Texture.PLANAR_MODE = 2;
  20961. Texture.CUBIC_MODE = 3;
  20962. Texture.PROJECTION_MODE = 4;
  20963. Texture.SKYBOX_MODE = 5;
  20964. Texture.INVCUBIC_MODE = 6;
  20965. Texture.EQUIRECTANGULAR_MODE = 7;
  20966. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20967. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  20968. Texture.CLAMP_ADDRESSMODE = 0;
  20969. Texture.WRAP_ADDRESSMODE = 1;
  20970. Texture.MIRROR_ADDRESSMODE = 2;
  20971. __decorate([
  20972. BABYLON.serialize()
  20973. ], Texture.prototype, "url", void 0);
  20974. __decorate([
  20975. BABYLON.serialize()
  20976. ], Texture.prototype, "uOffset", void 0);
  20977. __decorate([
  20978. BABYLON.serialize()
  20979. ], Texture.prototype, "vOffset", void 0);
  20980. __decorate([
  20981. BABYLON.serialize()
  20982. ], Texture.prototype, "uScale", void 0);
  20983. __decorate([
  20984. BABYLON.serialize()
  20985. ], Texture.prototype, "vScale", void 0);
  20986. __decorate([
  20987. BABYLON.serialize()
  20988. ], Texture.prototype, "uAng", void 0);
  20989. __decorate([
  20990. BABYLON.serialize()
  20991. ], Texture.prototype, "vAng", void 0);
  20992. __decorate([
  20993. BABYLON.serialize()
  20994. ], Texture.prototype, "wAng", void 0);
  20995. __decorate([
  20996. BABYLON.serialize()
  20997. ], Texture.prototype, "isBlocking", null);
  20998. return Texture;
  20999. }(BABYLON.BaseTexture));
  21000. BABYLON.Texture = Texture;
  21001. })(BABYLON || (BABYLON = {}));
  21002. //# sourceMappingURL=babylon.texture.js.map
  21003. var BABYLON;
  21004. (function (BABYLON) {
  21005. var _InstancesBatch = (function () {
  21006. function _InstancesBatch() {
  21007. this.mustReturn = false;
  21008. this.visibleInstances = new Array();
  21009. this.renderSelf = new Array();
  21010. }
  21011. return _InstancesBatch;
  21012. }());
  21013. BABYLON._InstancesBatch = _InstancesBatch;
  21014. var Mesh = (function (_super) {
  21015. __extends(Mesh, _super);
  21016. /**
  21017. * @constructor
  21018. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  21019. * @param {Scene} scene The scene to add this mesh to.
  21020. * @param {Node} parent The parent of this mesh, if it has one
  21021. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  21022. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  21023. * When false, achieved by calling a clone(), also passing False.
  21024. * This will make creation of children, recursive.
  21025. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  21026. */
  21027. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  21028. if (parent === void 0) { parent = null; }
  21029. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21030. var _this = _super.call(this, name, scene) || this;
  21031. // Events
  21032. /**
  21033. * An event triggered before rendering the mesh
  21034. * @type {BABYLON.Observable}
  21035. */
  21036. _this.onBeforeRenderObservable = new BABYLON.Observable();
  21037. /**
  21038. * An event triggered after rendering the mesh
  21039. * @type {BABYLON.Observable}
  21040. */
  21041. _this.onAfterRenderObservable = new BABYLON.Observable();
  21042. /**
  21043. * An event triggered before drawing the mesh
  21044. * @type {BABYLON.Observable}
  21045. */
  21046. _this.onBeforeDrawObservable = new BABYLON.Observable();
  21047. // Members
  21048. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21049. _this.instances = new Array();
  21050. _this._LODLevels = new Array();
  21051. _this._visibleInstances = {};
  21052. _this._renderIdForInstances = new Array();
  21053. _this._batchCache = new _InstancesBatch();
  21054. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  21055. _this._sideOrientation = Mesh._DEFAULTSIDE;
  21056. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  21057. // Will be used to save a source mesh reference, If any
  21058. _this._source = null;
  21059. if (source) {
  21060. // Source mesh
  21061. _this._source = source;
  21062. // Geometry
  21063. if (source._geometry) {
  21064. source._geometry.applyToMesh(_this);
  21065. }
  21066. // Deep copy
  21067. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  21068. // Parent
  21069. _this.parent = source.parent;
  21070. // Pivot
  21071. _this.setPivotMatrix(source.getPivotMatrix());
  21072. _this.id = name + "." + source.id;
  21073. // Material
  21074. _this.material = source.material;
  21075. var index;
  21076. if (!doNotCloneChildren) {
  21077. // Children
  21078. for (index = 0; index < scene.meshes.length; index++) {
  21079. var mesh = scene.meshes[index];
  21080. if (mesh.parent === source) {
  21081. // doNotCloneChildren is always going to be False
  21082. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  21083. }
  21084. }
  21085. }
  21086. // Physics clone
  21087. var physicsEngine = _this.getScene().getPhysicsEngine();
  21088. if (clonePhysicsImpostor && physicsEngine) {
  21089. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  21090. if (impostor) {
  21091. _this.physicsImpostor = impostor.clone(_this);
  21092. }
  21093. }
  21094. // Particles
  21095. for (index = 0; index < scene.particleSystems.length; index++) {
  21096. var system = scene.particleSystems[index];
  21097. if (system.emitter === source) {
  21098. system.clone(system.name, _this);
  21099. }
  21100. }
  21101. _this.computeWorldMatrix(true);
  21102. }
  21103. // Parent
  21104. if (parent !== null) {
  21105. _this.parent = parent;
  21106. }
  21107. return _this;
  21108. }
  21109. Object.defineProperty(Mesh, "FRONTSIDE", {
  21110. /**
  21111. * Mesh side orientation : usually the external or front surface
  21112. */
  21113. get: function () {
  21114. return Mesh._FRONTSIDE;
  21115. },
  21116. enumerable: true,
  21117. configurable: true
  21118. });
  21119. Object.defineProperty(Mesh, "BACKSIDE", {
  21120. /**
  21121. * Mesh side orientation : usually the internal or back surface
  21122. */
  21123. get: function () {
  21124. return Mesh._BACKSIDE;
  21125. },
  21126. enumerable: true,
  21127. configurable: true
  21128. });
  21129. Object.defineProperty(Mesh, "DOUBLESIDE", {
  21130. /**
  21131. * Mesh side orientation : both internal and external or front and back surfaces
  21132. */
  21133. get: function () {
  21134. return Mesh._DOUBLESIDE;
  21135. },
  21136. enumerable: true,
  21137. configurable: true
  21138. });
  21139. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  21140. /**
  21141. * Mesh side orientation : by default, `FRONTSIDE`
  21142. */
  21143. get: function () {
  21144. return Mesh._DEFAULTSIDE;
  21145. },
  21146. enumerable: true,
  21147. configurable: true
  21148. });
  21149. Object.defineProperty(Mesh, "NO_CAP", {
  21150. /**
  21151. * Mesh cap setting : no cap
  21152. */
  21153. get: function () {
  21154. return Mesh._NO_CAP;
  21155. },
  21156. enumerable: true,
  21157. configurable: true
  21158. });
  21159. Object.defineProperty(Mesh, "CAP_START", {
  21160. /**
  21161. * Mesh cap setting : one cap at the beginning of the mesh
  21162. */
  21163. get: function () {
  21164. return Mesh._CAP_START;
  21165. },
  21166. enumerable: true,
  21167. configurable: true
  21168. });
  21169. Object.defineProperty(Mesh, "CAP_END", {
  21170. /**
  21171. * Mesh cap setting : one cap at the end of the mesh
  21172. */
  21173. get: function () {
  21174. return Mesh._CAP_END;
  21175. },
  21176. enumerable: true,
  21177. configurable: true
  21178. });
  21179. Object.defineProperty(Mesh, "CAP_ALL", {
  21180. /**
  21181. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21182. */
  21183. get: function () {
  21184. return Mesh._CAP_ALL;
  21185. },
  21186. enumerable: true,
  21187. configurable: true
  21188. });
  21189. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21190. set: function (callback) {
  21191. if (this._onBeforeDrawObserver) {
  21192. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21193. }
  21194. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21195. },
  21196. enumerable: true,
  21197. configurable: true
  21198. });
  21199. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21200. get: function () {
  21201. return this._morphTargetManager;
  21202. },
  21203. set: function (value) {
  21204. if (this._morphTargetManager === value) {
  21205. return;
  21206. }
  21207. this._morphTargetManager = value;
  21208. this._syncGeometryWithMorphTargetManager();
  21209. },
  21210. enumerable: true,
  21211. configurable: true
  21212. });
  21213. Object.defineProperty(Mesh.prototype, "source", {
  21214. get: function () {
  21215. return this._source;
  21216. },
  21217. enumerable: true,
  21218. configurable: true
  21219. });
  21220. // Methods
  21221. /**
  21222. * Returns the string "Mesh".
  21223. */
  21224. Mesh.prototype.getClassName = function () {
  21225. return "Mesh";
  21226. };
  21227. /**
  21228. * Returns a string.
  21229. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21230. */
  21231. Mesh.prototype.toString = function (fullDetails) {
  21232. var ret = _super.prototype.toString.call(this, fullDetails);
  21233. ret += ", n vertices: " + this.getTotalVertices();
  21234. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21235. if (this.animations) {
  21236. for (var i = 0; i < this.animations.length; i++) {
  21237. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21238. }
  21239. }
  21240. if (fullDetails) {
  21241. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21242. }
  21243. return ret;
  21244. };
  21245. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21246. /**
  21247. * True if the mesh has some Levels Of Details (LOD).
  21248. * Returns a boolean.
  21249. */
  21250. get: function () {
  21251. return this._LODLevels.length > 0;
  21252. },
  21253. enumerable: true,
  21254. configurable: true
  21255. });
  21256. Mesh.prototype._sortLODLevels = function () {
  21257. this._LODLevels.sort(function (a, b) {
  21258. if (a.distance < b.distance) {
  21259. return 1;
  21260. }
  21261. if (a.distance > b.distance) {
  21262. return -1;
  21263. }
  21264. return 0;
  21265. });
  21266. };
  21267. /**
  21268. * Add a mesh as LOD level triggered at the given distance.
  21269. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21270. * @param {number} distance The distance from the center of the object to show this level
  21271. * @param {Mesh} mesh The mesh to be added as LOD level
  21272. * @return {Mesh} This mesh (for chaining)
  21273. */
  21274. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21275. if (mesh && mesh._masterMesh) {
  21276. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21277. return this;
  21278. }
  21279. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21280. this._LODLevels.push(level);
  21281. if (mesh) {
  21282. mesh._masterMesh = this;
  21283. }
  21284. this._sortLODLevels();
  21285. return this;
  21286. };
  21287. /**
  21288. * Returns the LOD level mesh at the passed distance or null if not found.
  21289. * It is related to the method `addLODLevel(distance, mesh)`.
  21290. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21291. * Returns an object Mesh or `null`.
  21292. */
  21293. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21294. for (var index = 0; index < this._LODLevels.length; index++) {
  21295. var level = this._LODLevels[index];
  21296. if (level.distance === distance) {
  21297. return level.mesh;
  21298. }
  21299. }
  21300. return null;
  21301. };
  21302. /**
  21303. * Remove a mesh from the LOD array
  21304. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21305. * @param {Mesh} mesh The mesh to be removed.
  21306. * @return {Mesh} This mesh (for chaining)
  21307. */
  21308. Mesh.prototype.removeLODLevel = function (mesh) {
  21309. for (var index = 0; index < this._LODLevels.length; index++) {
  21310. if (this._LODLevels[index].mesh === mesh) {
  21311. this._LODLevels.splice(index, 1);
  21312. if (mesh) {
  21313. mesh._masterMesh = null;
  21314. }
  21315. }
  21316. }
  21317. this._sortLODLevels();
  21318. return this;
  21319. };
  21320. /**
  21321. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21322. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21323. */
  21324. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21325. if (!this._LODLevels || this._LODLevels.length === 0) {
  21326. return this;
  21327. }
  21328. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21329. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21330. if (this.onLODLevelSelection) {
  21331. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21332. }
  21333. return this;
  21334. }
  21335. for (var index = 0; index < this._LODLevels.length; index++) {
  21336. var level = this._LODLevels[index];
  21337. if (level.distance < distanceToCamera) {
  21338. if (level.mesh) {
  21339. level.mesh._preActivate();
  21340. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21341. }
  21342. if (this.onLODLevelSelection) {
  21343. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21344. }
  21345. return level.mesh;
  21346. }
  21347. }
  21348. if (this.onLODLevelSelection) {
  21349. this.onLODLevelSelection(distanceToCamera, this, this);
  21350. }
  21351. return this;
  21352. };
  21353. Object.defineProperty(Mesh.prototype, "geometry", {
  21354. /**
  21355. * Returns the mesh internal Geometry object.
  21356. */
  21357. get: function () {
  21358. return this._geometry;
  21359. },
  21360. enumerable: true,
  21361. configurable: true
  21362. });
  21363. /**
  21364. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21365. */
  21366. Mesh.prototype.getTotalVertices = function () {
  21367. if (!this._geometry) {
  21368. return 0;
  21369. }
  21370. return this._geometry.getTotalVertices();
  21371. };
  21372. /**
  21373. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21374. * 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.
  21375. * You can force the copy with forceCopy === true
  21376. * Returns null if the mesh has no geometry or no vertex buffer.
  21377. * Possible `kind` values :
  21378. * - BABYLON.VertexBuffer.PositionKind
  21379. * - BABYLON.VertexBuffer.UVKind
  21380. * - BABYLON.VertexBuffer.UV2Kind
  21381. * - BABYLON.VertexBuffer.UV3Kind
  21382. * - BABYLON.VertexBuffer.UV4Kind
  21383. * - BABYLON.VertexBuffer.UV5Kind
  21384. * - BABYLON.VertexBuffer.UV6Kind
  21385. * - BABYLON.VertexBuffer.ColorKind
  21386. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21387. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21388. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21389. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21390. */
  21391. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21392. if (!this._geometry) {
  21393. return null;
  21394. }
  21395. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21396. };
  21397. /**
  21398. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21399. * Returns `undefined` if the mesh has no geometry.
  21400. * Possible `kind` values :
  21401. * - BABYLON.VertexBuffer.PositionKind
  21402. * - BABYLON.VertexBuffer.UVKind
  21403. * - BABYLON.VertexBuffer.UV2Kind
  21404. * - BABYLON.VertexBuffer.UV3Kind
  21405. * - BABYLON.VertexBuffer.UV4Kind
  21406. * - BABYLON.VertexBuffer.UV5Kind
  21407. * - BABYLON.VertexBuffer.UV6Kind
  21408. * - BABYLON.VertexBuffer.ColorKind
  21409. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21410. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21411. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21412. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21413. */
  21414. Mesh.prototype.getVertexBuffer = function (kind) {
  21415. if (!this._geometry) {
  21416. return undefined;
  21417. }
  21418. return this._geometry.getVertexBuffer(kind);
  21419. };
  21420. /**
  21421. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21422. * Possible `kind` values :
  21423. * - BABYLON.VertexBuffer.PositionKind
  21424. * - BABYLON.VertexBuffer.UVKind
  21425. * - BABYLON.VertexBuffer.UV2Kind
  21426. * - BABYLON.VertexBuffer.UV3Kind
  21427. * - BABYLON.VertexBuffer.UV4Kind
  21428. * - BABYLON.VertexBuffer.UV5Kind
  21429. * - BABYLON.VertexBuffer.UV6Kind
  21430. * - BABYLON.VertexBuffer.ColorKind
  21431. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21432. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21433. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21434. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21435. */
  21436. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21437. if (!this._geometry) {
  21438. if (this._delayInfo) {
  21439. return this._delayInfo.indexOf(kind) !== -1;
  21440. }
  21441. return false;
  21442. }
  21443. return this._geometry.isVerticesDataPresent(kind);
  21444. };
  21445. /**
  21446. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21447. * Possible `kind` values :
  21448. * - BABYLON.VertexBuffer.PositionKind
  21449. * - BABYLON.VertexBuffer.UVKind
  21450. * - BABYLON.VertexBuffer.UV2Kind
  21451. * - BABYLON.VertexBuffer.UV3Kind
  21452. * - BABYLON.VertexBuffer.UV4Kind
  21453. * - BABYLON.VertexBuffer.UV5Kind
  21454. * - BABYLON.VertexBuffer.UV6Kind
  21455. * - BABYLON.VertexBuffer.ColorKind
  21456. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21457. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21458. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21459. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21460. */
  21461. Mesh.prototype.getVerticesDataKinds = function () {
  21462. if (!this._geometry) {
  21463. var result = [];
  21464. if (this._delayInfo) {
  21465. this._delayInfo.forEach(function (kind, index, array) {
  21466. result.push(kind);
  21467. });
  21468. }
  21469. return result;
  21470. }
  21471. return this._geometry.getVerticesDataKinds();
  21472. };
  21473. /**
  21474. * Returns a positive integer : the total number of indices in this mesh geometry.
  21475. * Returns zero if the mesh has no geometry.
  21476. */
  21477. Mesh.prototype.getTotalIndices = function () {
  21478. if (!this._geometry) {
  21479. return 0;
  21480. }
  21481. return this._geometry.getTotalIndices();
  21482. };
  21483. /**
  21484. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21485. * 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.
  21486. * Returns an empty array if the mesh has no geometry.
  21487. */
  21488. Mesh.prototype.getIndices = function (copyWhenShared) {
  21489. if (!this._geometry) {
  21490. return [];
  21491. }
  21492. return this._geometry.getIndices(copyWhenShared);
  21493. };
  21494. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21495. get: function () {
  21496. return this._masterMesh !== null && this._masterMesh !== undefined;
  21497. },
  21498. enumerable: true,
  21499. configurable: true
  21500. });
  21501. /**
  21502. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21503. */
  21504. Mesh.prototype.isReady = function () {
  21505. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21506. return false;
  21507. }
  21508. return _super.prototype.isReady.call(this);
  21509. };
  21510. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  21511. get: function () {
  21512. return this._sideOrientation;
  21513. },
  21514. /**
  21515. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  21516. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  21517. */
  21518. set: function (sideO) {
  21519. this._sideOrientation = sideO;
  21520. },
  21521. enumerable: true,
  21522. configurable: true
  21523. });
  21524. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21525. /**
  21526. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21527. * This property is pertinent only for updatable parametric shapes.
  21528. */
  21529. get: function () {
  21530. return this._areNormalsFrozen;
  21531. },
  21532. enumerable: true,
  21533. configurable: true
  21534. });
  21535. /**
  21536. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21537. * It has no effect at all on other shapes.
  21538. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21539. * Returns the Mesh.
  21540. */
  21541. Mesh.prototype.freezeNormals = function () {
  21542. this._areNormalsFrozen = true;
  21543. return this;
  21544. };
  21545. /**
  21546. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21547. * It has no effect at all on other shapes.
  21548. * It reactivates the mesh normals computation if it was previously frozen.
  21549. * Returns the Mesh.
  21550. */
  21551. Mesh.prototype.unfreezeNormals = function () {
  21552. this._areNormalsFrozen = false;
  21553. return this;
  21554. };
  21555. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21556. /**
  21557. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21558. */
  21559. set: function (count) {
  21560. this._overridenInstanceCount = count;
  21561. },
  21562. enumerable: true,
  21563. configurable: true
  21564. });
  21565. // Methods
  21566. Mesh.prototype._preActivate = function () {
  21567. var sceneRenderId = this.getScene().getRenderId();
  21568. if (this._preActivateId === sceneRenderId) {
  21569. return this;
  21570. }
  21571. this._preActivateId = sceneRenderId;
  21572. this._visibleInstances = null;
  21573. return this;
  21574. };
  21575. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21576. if (this._visibleInstances) {
  21577. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21578. }
  21579. return this;
  21580. };
  21581. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21582. if (!this._visibleInstances) {
  21583. this._visibleInstances = {};
  21584. this._visibleInstances.defaultRenderId = renderId;
  21585. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21586. }
  21587. if (!this._visibleInstances[renderId]) {
  21588. this._visibleInstances[renderId] = new Array();
  21589. }
  21590. this._visibleInstances[renderId].push(instance);
  21591. return this;
  21592. };
  21593. /**
  21594. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21595. * This means the mesh underlying bounding box and sphere are recomputed.
  21596. * Returns the Mesh.
  21597. */
  21598. Mesh.prototype.refreshBoundingInfo = function () {
  21599. if (this._boundingInfo.isLocked) {
  21600. return;
  21601. }
  21602. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21603. if (data) {
  21604. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21605. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21606. }
  21607. if (this.subMeshes) {
  21608. for (var index = 0; index < this.subMeshes.length; index++) {
  21609. this.subMeshes[index].refreshBoundingInfo();
  21610. }
  21611. }
  21612. this._updateBoundingInfo();
  21613. return this;
  21614. };
  21615. Mesh.prototype._createGlobalSubMesh = function (force) {
  21616. var totalVertices = this.getTotalVertices();
  21617. if (!totalVertices || !this.getIndices()) {
  21618. return null;
  21619. }
  21620. // Check if we need to recreate the submeshes
  21621. if (this.subMeshes && this.subMeshes.length > 0) {
  21622. var totalIndices = this.getIndices().length;
  21623. var needToRecreate = false;
  21624. if (force) {
  21625. needToRecreate = true;
  21626. }
  21627. else {
  21628. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21629. var submesh = _a[_i];
  21630. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21631. needToRecreate = true;
  21632. break;
  21633. }
  21634. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21635. needToRecreate = true;
  21636. break;
  21637. }
  21638. }
  21639. }
  21640. if (!needToRecreate) {
  21641. return;
  21642. }
  21643. }
  21644. this.releaseSubMeshes();
  21645. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21646. };
  21647. Mesh.prototype.subdivide = function (count) {
  21648. if (count < 1) {
  21649. return;
  21650. }
  21651. var totalIndices = this.getTotalIndices();
  21652. var subdivisionSize = (totalIndices / count) | 0;
  21653. var offset = 0;
  21654. // Ensure that subdivisionSize is a multiple of 3
  21655. while (subdivisionSize % 3 !== 0) {
  21656. subdivisionSize++;
  21657. }
  21658. this.releaseSubMeshes();
  21659. for (var index = 0; index < count; index++) {
  21660. if (offset >= totalIndices) {
  21661. break;
  21662. }
  21663. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21664. offset += subdivisionSize;
  21665. }
  21666. this.synchronizeInstances();
  21667. };
  21668. /**
  21669. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21670. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21671. * The `data` are either a numeric array either a Float32Array.
  21672. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21673. * 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).
  21674. * Note that a new underlying VertexBuffer object is created each call.
  21675. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21676. *
  21677. * Possible `kind` values :
  21678. * - BABYLON.VertexBuffer.PositionKind
  21679. * - BABYLON.VertexBuffer.UVKind
  21680. * - BABYLON.VertexBuffer.UV2Kind
  21681. * - BABYLON.VertexBuffer.UV3Kind
  21682. * - BABYLON.VertexBuffer.UV4Kind
  21683. * - BABYLON.VertexBuffer.UV5Kind
  21684. * - BABYLON.VertexBuffer.UV6Kind
  21685. * - BABYLON.VertexBuffer.ColorKind
  21686. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21687. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21688. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21689. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21690. *
  21691. * Returns the Mesh.
  21692. */
  21693. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21694. if (!this._geometry) {
  21695. var vertexData = new BABYLON.VertexData();
  21696. vertexData.set(data, kind);
  21697. var scene = this.getScene();
  21698. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21699. }
  21700. else {
  21701. this._geometry.setVerticesData(kind, data, updatable, stride);
  21702. }
  21703. return this;
  21704. };
  21705. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21706. if (updatable === void 0) { updatable = true; }
  21707. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21708. return;
  21709. }
  21710. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21711. };
  21712. /**
  21713. * Sets the mesh VertexBuffer.
  21714. * Returns the Mesh.
  21715. */
  21716. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21717. if (!this._geometry) {
  21718. var scene = this.getScene();
  21719. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21720. }
  21721. this._geometry.setVerticesBuffer(buffer);
  21722. return this;
  21723. };
  21724. /**
  21725. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21726. * If the mesh has no geometry, it is simply returned as it is.
  21727. * The `data` are either a numeric array either a Float32Array.
  21728. * No new underlying VertexBuffer object is created.
  21729. * 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.
  21730. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21731. *
  21732. * Possible `kind` values :
  21733. * - BABYLON.VertexBuffer.PositionKind
  21734. * - BABYLON.VertexBuffer.UVKind
  21735. * - BABYLON.VertexBuffer.UV2Kind
  21736. * - BABYLON.VertexBuffer.UV3Kind
  21737. * - BABYLON.VertexBuffer.UV4Kind
  21738. * - BABYLON.VertexBuffer.UV5Kind
  21739. * - BABYLON.VertexBuffer.UV6Kind
  21740. * - BABYLON.VertexBuffer.ColorKind
  21741. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21742. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21743. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21744. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21745. *
  21746. * Returns the Mesh.
  21747. */
  21748. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21749. if (!this._geometry) {
  21750. return;
  21751. }
  21752. if (!makeItUnique) {
  21753. this._geometry.updateVerticesData(kind, data, updateExtends);
  21754. }
  21755. else {
  21756. this.makeGeometryUnique();
  21757. this.updateVerticesData(kind, data, updateExtends, false);
  21758. }
  21759. return this;
  21760. };
  21761. /**
  21762. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21763. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21764. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21765. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21766. * Returns the Mesh.
  21767. */
  21768. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21769. if (computeNormals === void 0) { computeNormals = true; }
  21770. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21771. positionFunction(positions);
  21772. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21773. if (computeNormals) {
  21774. var indices = this.getIndices();
  21775. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21776. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21777. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21778. }
  21779. return this;
  21780. };
  21781. /**
  21782. * Creates a un-shared specific occurence of the geometry for the mesh.
  21783. * Returns the Mesh.
  21784. */
  21785. Mesh.prototype.makeGeometryUnique = function () {
  21786. if (!this._geometry) {
  21787. return;
  21788. }
  21789. var oldGeometry = this._geometry;
  21790. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21791. oldGeometry.releaseForMesh(this, true);
  21792. geometry.applyToMesh(this);
  21793. return this;
  21794. };
  21795. /**
  21796. * Sets the mesh indices.
  21797. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21798. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21799. * This method creates a new index buffer each call.
  21800. * Returns the Mesh.
  21801. */
  21802. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21803. if (!this._geometry) {
  21804. var vertexData = new BABYLON.VertexData();
  21805. vertexData.indices = indices;
  21806. var scene = this.getScene();
  21807. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21808. }
  21809. else {
  21810. this._geometry.setIndices(indices, totalVertices);
  21811. }
  21812. return this;
  21813. };
  21814. /**
  21815. * Invert the geometry to move from a right handed system to a left handed one.
  21816. * Returns the Mesh.
  21817. */
  21818. Mesh.prototype.toLeftHanded = function () {
  21819. if (!this._geometry) {
  21820. return;
  21821. }
  21822. this._geometry.toLeftHanded();
  21823. return this;
  21824. };
  21825. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21826. var engine = this.getScene().getEngine();
  21827. // Wireframe
  21828. var indexToBind;
  21829. if (this._unIndexed) {
  21830. indexToBind = null;
  21831. }
  21832. else {
  21833. switch (fillMode) {
  21834. case BABYLON.Material.PointFillMode:
  21835. indexToBind = null;
  21836. break;
  21837. case BABYLON.Material.WireFrameFillMode:
  21838. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21839. break;
  21840. default:
  21841. case BABYLON.Material.TriangleFillMode:
  21842. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21843. break;
  21844. }
  21845. }
  21846. // VBOs
  21847. this._geometry._bind(effect, indexToBind);
  21848. return this;
  21849. };
  21850. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21851. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21852. return this;
  21853. }
  21854. this.onBeforeDrawObservable.notifyObservers(this);
  21855. var engine = this.getScene().getEngine();
  21856. // Draw order
  21857. switch (fillMode) {
  21858. case BABYLON.Material.PointFillMode:
  21859. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21860. break;
  21861. case BABYLON.Material.WireFrameFillMode:
  21862. if (this._unIndexed) {
  21863. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21864. }
  21865. else {
  21866. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  21867. }
  21868. break;
  21869. default:
  21870. if (this._unIndexed) {
  21871. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21872. }
  21873. else {
  21874. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21875. }
  21876. }
  21877. return this;
  21878. };
  21879. /**
  21880. * Registers for this mesh a javascript function called just before the rendering process.
  21881. * This function is passed the current mesh.
  21882. * Return the Mesh.
  21883. */
  21884. Mesh.prototype.registerBeforeRender = function (func) {
  21885. this.onBeforeRenderObservable.add(func);
  21886. return this;
  21887. };
  21888. /**
  21889. * Disposes a previously registered javascript function called before the rendering.
  21890. * This function is passed the current mesh.
  21891. * Returns the Mesh.
  21892. */
  21893. Mesh.prototype.unregisterBeforeRender = function (func) {
  21894. this.onBeforeRenderObservable.removeCallback(func);
  21895. return this;
  21896. };
  21897. /**
  21898. * Registers for this mesh a javascript function called just after the rendering is complete.
  21899. * This function is passed the current mesh.
  21900. * Returns the Mesh.
  21901. */
  21902. Mesh.prototype.registerAfterRender = function (func) {
  21903. this.onAfterRenderObservable.add(func);
  21904. return this;
  21905. };
  21906. /**
  21907. * Disposes a previously registered javascript function called after the rendering.
  21908. * This function is passed the current mesh.
  21909. * Return the Mesh.
  21910. */
  21911. Mesh.prototype.unregisterAfterRender = function (func) {
  21912. this.onAfterRenderObservable.removeCallback(func);
  21913. return this;
  21914. };
  21915. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21916. var scene = this.getScene();
  21917. this._batchCache.mustReturn = false;
  21918. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21919. this._batchCache.visibleInstances[subMeshId] = null;
  21920. if (this._visibleInstances) {
  21921. var currentRenderId = scene.getRenderId();
  21922. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21923. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21924. var selfRenderId = this._renderId;
  21925. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21926. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21927. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21928. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21929. }
  21930. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21931. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21932. this._batchCache.mustReturn = true;
  21933. return this._batchCache;
  21934. }
  21935. if (currentRenderId !== selfRenderId) {
  21936. this._batchCache.renderSelf[subMeshId] = false;
  21937. }
  21938. }
  21939. this._renderIdForInstances[subMeshId] = currentRenderId;
  21940. }
  21941. return this._batchCache;
  21942. };
  21943. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21944. var visibleInstances = batch.visibleInstances[subMesh._id];
  21945. var matricesCount = visibleInstances.length + 1;
  21946. var bufferSize = matricesCount * 16 * 4;
  21947. var currentInstancesBufferSize = this._instancesBufferSize;
  21948. var instancesBuffer = this._instancesBuffer;
  21949. while (this._instancesBufferSize < bufferSize) {
  21950. this._instancesBufferSize *= 2;
  21951. }
  21952. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21953. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21954. }
  21955. var offset = 0;
  21956. var instancesCount = 0;
  21957. var world = this.getWorldMatrix();
  21958. if (batch.renderSelf[subMesh._id]) {
  21959. world.copyToArray(this._instancesData, offset);
  21960. offset += 16;
  21961. instancesCount++;
  21962. }
  21963. if (visibleInstances) {
  21964. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21965. var instance = visibleInstances[instanceIndex];
  21966. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21967. offset += 16;
  21968. instancesCount++;
  21969. }
  21970. }
  21971. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21972. if (instancesBuffer) {
  21973. instancesBuffer.dispose();
  21974. }
  21975. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21976. this._instancesBuffer = instancesBuffer;
  21977. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21978. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21979. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21980. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21981. }
  21982. else {
  21983. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21984. }
  21985. this._bind(subMesh, effect, fillMode);
  21986. this._draw(subMesh, fillMode, instancesCount);
  21987. engine.unbindInstanceAttributes();
  21988. return this;
  21989. };
  21990. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21991. var scene = this.getScene();
  21992. var engine = scene.getEngine();
  21993. if (hardwareInstancedRendering) {
  21994. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21995. }
  21996. else {
  21997. if (batch.renderSelf[subMesh._id]) {
  21998. // Draw
  21999. if (onBeforeDraw) {
  22000. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  22001. }
  22002. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  22003. }
  22004. if (batch.visibleInstances[subMesh._id]) {
  22005. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22006. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22007. // World
  22008. var world = instance.getWorldMatrix();
  22009. if (onBeforeDraw) {
  22010. onBeforeDraw(true, world, effectiveMaterial);
  22011. }
  22012. // Draw
  22013. this._draw(subMesh, fillMode);
  22014. }
  22015. }
  22016. }
  22017. return this;
  22018. };
  22019. /**
  22020. * Triggers the draw call for the mesh.
  22021. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  22022. * Returns the Mesh.
  22023. */
  22024. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  22025. this.checkOcclusionQuery();
  22026. if (this._isOccluded) {
  22027. return;
  22028. }
  22029. var scene = this.getScene();
  22030. // Managing instances
  22031. var batch = this._getInstancesRenderList(subMesh._id);
  22032. if (batch.mustReturn) {
  22033. return this;
  22034. }
  22035. // Checking geometry state
  22036. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22037. return this;
  22038. }
  22039. var callbackIndex;
  22040. this.onBeforeRenderObservable.notifyObservers(this);
  22041. var engine = scene.getEngine();
  22042. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  22043. // Material
  22044. var effectiveMaterial = subMesh.getMaterial();
  22045. if (!effectiveMaterial) {
  22046. return this;
  22047. }
  22048. if (effectiveMaterial.storeEffectOnSubMeshes) {
  22049. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  22050. return this;
  22051. }
  22052. }
  22053. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  22054. return this;
  22055. }
  22056. // Alpha mode
  22057. if (enableAlphaMode) {
  22058. engine.setAlphaMode(effectiveMaterial.alphaMode);
  22059. }
  22060. // Outline - step 1
  22061. var savedDepthWrite = engine.getDepthWrite();
  22062. if (this.renderOutline) {
  22063. engine.setDepthWrite(false);
  22064. scene.getOutlineRenderer().render(subMesh, batch);
  22065. engine.setDepthWrite(savedDepthWrite);
  22066. }
  22067. var effect;
  22068. if (effectiveMaterial.storeEffectOnSubMeshes) {
  22069. effect = subMesh.effect;
  22070. }
  22071. else {
  22072. effect = effectiveMaterial.getEffect();
  22073. }
  22074. effectiveMaterial._preBind(effect);
  22075. // Bind
  22076. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  22077. if (!hardwareInstancedRendering) {
  22078. this._bind(subMesh, effect, fillMode);
  22079. }
  22080. var world = this.getWorldMatrix();
  22081. if (effectiveMaterial.storeEffectOnSubMeshes) {
  22082. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  22083. }
  22084. else {
  22085. effectiveMaterial.bind(world, this);
  22086. }
  22087. // Draw
  22088. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  22089. // Unbind
  22090. effectiveMaterial.unbind();
  22091. // Outline - step 2
  22092. if (this.renderOutline && savedDepthWrite) {
  22093. engine.setDepthWrite(true);
  22094. engine.setColorWrite(false);
  22095. scene.getOutlineRenderer().render(subMesh, batch);
  22096. engine.setColorWrite(true);
  22097. }
  22098. // Overlay
  22099. if (this.renderOverlay) {
  22100. var currentMode = engine.getAlphaMode();
  22101. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22102. scene.getOutlineRenderer().render(subMesh, batch, true);
  22103. engine.setAlphaMode(currentMode);
  22104. }
  22105. this.onAfterRenderObservable.notifyObservers(this);
  22106. return this;
  22107. };
  22108. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  22109. if (isInstance) {
  22110. effectiveMaterial.bindOnlyWorldMatrix(world);
  22111. }
  22112. return this;
  22113. };
  22114. /**
  22115. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  22116. */
  22117. Mesh.prototype.getEmittedParticleSystems = function () {
  22118. var results = new Array();
  22119. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22120. var particleSystem = this.getScene().particleSystems[index];
  22121. if (particleSystem.emitter === this) {
  22122. results.push(particleSystem);
  22123. }
  22124. }
  22125. return results;
  22126. };
  22127. /**
  22128. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  22129. */
  22130. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  22131. var results = new Array();
  22132. var descendants = this.getDescendants();
  22133. descendants.push(this);
  22134. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22135. var particleSystem = this.getScene().particleSystems[index];
  22136. var emitter = particleSystem.emitter;
  22137. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  22138. results.push(particleSystem);
  22139. }
  22140. }
  22141. return results;
  22142. };
  22143. Mesh.prototype._checkDelayState = function () {
  22144. var scene = this.getScene();
  22145. if (this._geometry) {
  22146. this._geometry.load(scene);
  22147. }
  22148. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22149. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22150. this._queueLoad(this, scene);
  22151. }
  22152. return this;
  22153. };
  22154. Mesh.prototype._queueLoad = function (mesh, scene) {
  22155. var _this = this;
  22156. scene._addPendingData(mesh);
  22157. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  22158. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22159. if (data instanceof ArrayBuffer) {
  22160. _this._delayLoadingFunction(data, _this);
  22161. }
  22162. else {
  22163. _this._delayLoadingFunction(JSON.parse(data), _this);
  22164. }
  22165. _this.instances.forEach(function (instance) {
  22166. instance._syncSubMeshes();
  22167. });
  22168. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22169. scene._removePendingData(_this);
  22170. }, function () { }, scene.database, getBinaryData);
  22171. return this;
  22172. };
  22173. /**
  22174. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  22175. */
  22176. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22177. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22178. return false;
  22179. }
  22180. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22181. return false;
  22182. }
  22183. this._checkDelayState();
  22184. return true;
  22185. };
  22186. /**
  22187. * Sets the mesh material by the material or multiMaterial `id` property.
  22188. * The material `id` is a string identifying the material or the multiMaterial.
  22189. * This method returns the Mesh.
  22190. */
  22191. Mesh.prototype.setMaterialByID = function (id) {
  22192. var materials = this.getScene().materials;
  22193. var index;
  22194. for (index = materials.length - 1; index > -1; index--) {
  22195. if (materials[index].id === id) {
  22196. this.material = materials[index];
  22197. return this;
  22198. }
  22199. }
  22200. // Multi
  22201. var multiMaterials = this.getScene().multiMaterials;
  22202. for (index = multiMaterials.length - 1; index > -1; index--) {
  22203. if (multiMaterials[index].id === id) {
  22204. this.material = multiMaterials[index];
  22205. return this;
  22206. }
  22207. }
  22208. return this;
  22209. };
  22210. /**
  22211. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22212. */
  22213. Mesh.prototype.getAnimatables = function () {
  22214. var results = [];
  22215. if (this.material) {
  22216. results.push(this.material);
  22217. }
  22218. if (this.skeleton) {
  22219. results.push(this.skeleton);
  22220. }
  22221. return results;
  22222. };
  22223. /**
  22224. * Modifies the mesh geometry according to the passed transformation matrix.
  22225. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22226. * The mesh normals are modified accordingly the same transformation.
  22227. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22228. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22229. * Returns the Mesh.
  22230. */
  22231. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22232. // Position
  22233. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22234. return this;
  22235. }
  22236. var submeshes = this.subMeshes.splice(0);
  22237. this._resetPointsArrayCache();
  22238. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22239. var temp = [];
  22240. var index;
  22241. for (index = 0; index < data.length; index += 3) {
  22242. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22243. }
  22244. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22245. // Normals
  22246. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22247. return this;
  22248. }
  22249. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22250. temp = [];
  22251. for (index = 0; index < data.length; index += 3) {
  22252. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22253. }
  22254. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22255. // flip faces?
  22256. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22257. this.flipFaces();
  22258. }
  22259. // Restore submeshes
  22260. this.releaseSubMeshes();
  22261. this.subMeshes = submeshes;
  22262. return this;
  22263. };
  22264. /**
  22265. * Modifies the mesh geometry according to its own current World Matrix.
  22266. * The mesh World Matrix is then reset.
  22267. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22268. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22269. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22270. * Returns the Mesh.
  22271. */
  22272. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22273. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22274. this.scaling.copyFromFloats(1, 1, 1);
  22275. this.position.copyFromFloats(0, 0, 0);
  22276. this.rotation.copyFromFloats(0, 0, 0);
  22277. //only if quaternion is already set
  22278. if (this.rotationQuaternion) {
  22279. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22280. }
  22281. this._worldMatrix = BABYLON.Matrix.Identity();
  22282. return this;
  22283. };
  22284. Object.defineProperty(Mesh.prototype, "_positions", {
  22285. // Cache
  22286. get: function () {
  22287. if (this._geometry) {
  22288. return this._geometry._positions;
  22289. }
  22290. return null;
  22291. },
  22292. enumerable: true,
  22293. configurable: true
  22294. });
  22295. Mesh.prototype._resetPointsArrayCache = function () {
  22296. if (this._geometry) {
  22297. this._geometry._resetPointsArrayCache();
  22298. }
  22299. return this;
  22300. };
  22301. Mesh.prototype._generatePointsArray = function () {
  22302. if (this._geometry) {
  22303. return this._geometry._generatePointsArray();
  22304. }
  22305. return false;
  22306. };
  22307. /**
  22308. * Returns a new Mesh object generated from the current mesh properties.
  22309. * This method must not get confused with createInstance().
  22310. * The parameter `name` is a string, the name given to the new mesh.
  22311. * The optional parameter `newParent` can be any Node object (default `null`).
  22312. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22313. * 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.
  22314. */
  22315. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22316. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22317. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22318. };
  22319. /**
  22320. * Disposes the mesh.
  22321. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22322. */
  22323. Mesh.prototype.dispose = function (doNotRecurse) {
  22324. var _this = this;
  22325. this.morphTargetManager = undefined;
  22326. if (this._geometry) {
  22327. this._geometry.releaseForMesh(this, true);
  22328. }
  22329. // Sources
  22330. var meshes = this.getScene().meshes;
  22331. meshes.forEach(function (mesh) {
  22332. if (mesh._source && mesh._source === _this) {
  22333. mesh._source = null;
  22334. }
  22335. });
  22336. this._source = null;
  22337. // Instances
  22338. if (this._instancesBuffer) {
  22339. this._instancesBuffer.dispose();
  22340. this._instancesBuffer = null;
  22341. }
  22342. while (this.instances.length) {
  22343. this.instances[0].dispose();
  22344. }
  22345. // Highlight layers.
  22346. var highlightLayers = this.getScene().highlightLayers;
  22347. for (var i = 0; i < highlightLayers.length; i++) {
  22348. var highlightLayer = highlightLayers[i];
  22349. if (highlightLayer) {
  22350. highlightLayer.removeMesh(this);
  22351. highlightLayer.removeExcludedMesh(this);
  22352. }
  22353. }
  22354. _super.prototype.dispose.call(this, doNotRecurse);
  22355. };
  22356. /**
  22357. * Modifies the mesh geometry according to a displacement map.
  22358. * 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.
  22359. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22360. * This method returns nothing.
  22361. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22362. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22363. * 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.
  22364. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22365. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22366. *
  22367. * Returns the Mesh.
  22368. */
  22369. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22370. var _this = this;
  22371. var scene = this.getScene();
  22372. var onload = function (img) {
  22373. // Getting height map data
  22374. var canvas = document.createElement("canvas");
  22375. var context = canvas.getContext("2d");
  22376. var heightMapWidth = img.width;
  22377. var heightMapHeight = img.height;
  22378. canvas.width = heightMapWidth;
  22379. canvas.height = heightMapHeight;
  22380. context.drawImage(img, 0, 0);
  22381. // Create VertexData from map data
  22382. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22383. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22384. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22385. //execute success callback, if set
  22386. if (onSuccess) {
  22387. onSuccess(_this);
  22388. }
  22389. };
  22390. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22391. return this;
  22392. };
  22393. /**
  22394. * Modifies the mesh geometry according to a displacementMap buffer.
  22395. * 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.
  22396. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22397. * This method returns nothing.
  22398. * 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.
  22399. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22400. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22401. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22402. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22403. *
  22404. * Returns the Mesh.
  22405. */
  22406. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22407. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22408. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22409. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22410. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22411. return this;
  22412. }
  22413. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22414. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22415. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22416. var position = BABYLON.Vector3.Zero();
  22417. var normal = BABYLON.Vector3.Zero();
  22418. var uv = BABYLON.Vector2.Zero();
  22419. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22420. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22421. for (var index = 0; index < positions.length; index += 3) {
  22422. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22423. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22424. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22425. // Compute height
  22426. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22427. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22428. var pos = (u + v * heightMapWidth) * 4;
  22429. var r = buffer[pos] / 255.0;
  22430. var g = buffer[pos + 1] / 255.0;
  22431. var b = buffer[pos + 2] / 255.0;
  22432. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22433. normal.normalize();
  22434. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22435. position = position.add(normal);
  22436. position.toArray(positions, index);
  22437. }
  22438. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22439. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22440. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22441. return this;
  22442. };
  22443. /**
  22444. * Modify the mesh to get a flat shading rendering.
  22445. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22446. * This method returns the Mesh.
  22447. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22448. */
  22449. Mesh.prototype.convertToFlatShadedMesh = function () {
  22450. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22451. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22452. var kinds = this.getVerticesDataKinds();
  22453. var vbs = [];
  22454. var data = [];
  22455. var newdata = [];
  22456. var updatableNormals = false;
  22457. var kindIndex;
  22458. var kind;
  22459. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22460. kind = kinds[kindIndex];
  22461. var vertexBuffer = this.getVertexBuffer(kind);
  22462. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22463. updatableNormals = vertexBuffer.isUpdatable();
  22464. kinds.splice(kindIndex, 1);
  22465. kindIndex--;
  22466. continue;
  22467. }
  22468. vbs[kind] = vertexBuffer;
  22469. data[kind] = vbs[kind].getData();
  22470. newdata[kind] = [];
  22471. }
  22472. // Save previous submeshes
  22473. var previousSubmeshes = this.subMeshes.slice(0);
  22474. var indices = this.getIndices();
  22475. var totalIndices = this.getTotalIndices();
  22476. // Generating unique vertices per face
  22477. var index;
  22478. for (index = 0; index < totalIndices; index++) {
  22479. var vertexIndex = indices[index];
  22480. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22481. kind = kinds[kindIndex];
  22482. var stride = vbs[kind].getStrideSize();
  22483. for (var offset = 0; offset < stride; offset++) {
  22484. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22485. }
  22486. }
  22487. }
  22488. // Updating faces & normal
  22489. var normals = [];
  22490. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22491. for (index = 0; index < totalIndices; index += 3) {
  22492. indices[index] = index;
  22493. indices[index + 1] = index + 1;
  22494. indices[index + 2] = index + 2;
  22495. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22496. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22497. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22498. var p1p2 = p1.subtract(p2);
  22499. var p3p2 = p3.subtract(p2);
  22500. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22501. // Store same normals for every vertex
  22502. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22503. normals.push(normal.x);
  22504. normals.push(normal.y);
  22505. normals.push(normal.z);
  22506. }
  22507. }
  22508. this.setIndices(indices);
  22509. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22510. // Updating vertex buffers
  22511. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22512. kind = kinds[kindIndex];
  22513. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22514. }
  22515. // Updating submeshes
  22516. this.releaseSubMeshes();
  22517. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22518. var previousOne = previousSubmeshes[submeshIndex];
  22519. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22520. }
  22521. this.synchronizeInstances();
  22522. return this;
  22523. };
  22524. /**
  22525. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22526. * In other words, more vertices, no more indices and a single bigger VBO.
  22527. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22528. * Returns the Mesh.
  22529. */
  22530. Mesh.prototype.convertToUnIndexedMesh = function () {
  22531. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22532. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22533. var kinds = this.getVerticesDataKinds();
  22534. var vbs = [];
  22535. var data = [];
  22536. var newdata = [];
  22537. var updatableNormals = false;
  22538. var kindIndex;
  22539. var kind;
  22540. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22541. kind = kinds[kindIndex];
  22542. var vertexBuffer = this.getVertexBuffer(kind);
  22543. vbs[kind] = vertexBuffer;
  22544. data[kind] = vbs[kind].getData();
  22545. newdata[kind] = [];
  22546. }
  22547. // Save previous submeshes
  22548. var previousSubmeshes = this.subMeshes.slice(0);
  22549. var indices = this.getIndices();
  22550. var totalIndices = this.getTotalIndices();
  22551. // Generating unique vertices per face
  22552. var index;
  22553. for (index = 0; index < totalIndices; index++) {
  22554. var vertexIndex = indices[index];
  22555. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22556. kind = kinds[kindIndex];
  22557. var stride = vbs[kind].getStrideSize();
  22558. for (var offset = 0; offset < stride; offset++) {
  22559. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22560. }
  22561. }
  22562. }
  22563. // Updating indices
  22564. for (index = 0; index < totalIndices; index += 3) {
  22565. indices[index] = index;
  22566. indices[index + 1] = index + 1;
  22567. indices[index + 2] = index + 2;
  22568. }
  22569. this.setIndices(indices);
  22570. // Updating vertex buffers
  22571. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22572. kind = kinds[kindIndex];
  22573. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22574. }
  22575. // Updating submeshes
  22576. this.releaseSubMeshes();
  22577. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22578. var previousOne = previousSubmeshes[submeshIndex];
  22579. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22580. }
  22581. this._unIndexed = true;
  22582. this.synchronizeInstances();
  22583. return this;
  22584. };
  22585. /**
  22586. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22587. * This method returns the Mesh.
  22588. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22589. */
  22590. Mesh.prototype.flipFaces = function (flipNormals) {
  22591. if (flipNormals === void 0) { flipNormals = false; }
  22592. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22593. var i;
  22594. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22595. for (i = 0; i < vertex_data.normals.length; i++) {
  22596. vertex_data.normals[i] *= -1;
  22597. }
  22598. }
  22599. var temp;
  22600. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22601. // reassign indices
  22602. temp = vertex_data.indices[i + 1];
  22603. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22604. vertex_data.indices[i + 2] = temp;
  22605. }
  22606. vertex_data.applyToMesh(this);
  22607. return this;
  22608. };
  22609. // Instances
  22610. /**
  22611. * Creates a new InstancedMesh object from the mesh model.
  22612. * An instance shares the same properties and the same material than its model.
  22613. * Only these properties of each instance can then be set individually :
  22614. * - position
  22615. * - rotation
  22616. * - rotationQuaternion
  22617. * - setPivotMatrix
  22618. * - scaling
  22619. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22620. * Warning : this method is not supported for Line mesh and LineSystem
  22621. */
  22622. Mesh.prototype.createInstance = function (name) {
  22623. return new BABYLON.InstancedMesh(name, this);
  22624. };
  22625. /**
  22626. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22627. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22628. * This method returns the Mesh.
  22629. */
  22630. Mesh.prototype.synchronizeInstances = function () {
  22631. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22632. var instance = this.instances[instanceIndex];
  22633. instance._syncSubMeshes();
  22634. }
  22635. return this;
  22636. };
  22637. /**
  22638. * Simplify the mesh according to the given array of settings.
  22639. * Function will return immediately and will simplify async. It returns the Mesh.
  22640. * @param settings a collection of simplification settings.
  22641. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22642. * @param type the type of simplification to run.
  22643. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22644. */
  22645. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22646. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22647. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22648. this.getScene().simplificationQueue.addTask({
  22649. settings: settings,
  22650. parallelProcessing: parallelProcessing,
  22651. mesh: this,
  22652. simplificationType: simplificationType,
  22653. successCallback: successCallback
  22654. });
  22655. return this;
  22656. };
  22657. /**
  22658. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22659. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22660. * This should be used together with the simplification to avoid disappearing triangles.
  22661. * Returns the Mesh.
  22662. * @param successCallback an optional success callback to be called after the optimization finished.
  22663. */
  22664. Mesh.prototype.optimizeIndices = function (successCallback) {
  22665. var _this = this;
  22666. var indices = this.getIndices();
  22667. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22668. var vectorPositions = [];
  22669. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22670. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22671. }
  22672. var dupes = [];
  22673. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22674. var realPos = vectorPositions.length - 1 - iteration;
  22675. var testedPosition = vectorPositions[realPos];
  22676. for (var j = 0; j < realPos; ++j) {
  22677. var againstPosition = vectorPositions[j];
  22678. if (testedPosition.equals(againstPosition)) {
  22679. dupes[realPos] = j;
  22680. break;
  22681. }
  22682. }
  22683. }, function () {
  22684. for (var i = 0; i < indices.length; ++i) {
  22685. indices[i] = dupes[indices[i]] || indices[i];
  22686. }
  22687. //indices are now reordered
  22688. var originalSubMeshes = _this.subMeshes.slice(0);
  22689. _this.setIndices(indices);
  22690. _this.subMeshes = originalSubMeshes;
  22691. if (successCallback) {
  22692. successCallback(_this);
  22693. }
  22694. });
  22695. return this;
  22696. };
  22697. Mesh.prototype.serialize = function (serializationObject) {
  22698. serializationObject.name = this.name;
  22699. serializationObject.id = this.id;
  22700. serializationObject.type = this.getClassName();
  22701. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22702. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22703. }
  22704. serializationObject.position = this.position.asArray();
  22705. if (this.rotationQuaternion) {
  22706. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22707. }
  22708. else if (this.rotation) {
  22709. serializationObject.rotation = this.rotation.asArray();
  22710. }
  22711. serializationObject.scaling = this.scaling.asArray();
  22712. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22713. serializationObject.isEnabled = this.isEnabled();
  22714. serializationObject.isVisible = this.isVisible;
  22715. serializationObject.infiniteDistance = this.infiniteDistance;
  22716. serializationObject.pickable = this.isPickable;
  22717. serializationObject.receiveShadows = this.receiveShadows;
  22718. serializationObject.billboardMode = this.billboardMode;
  22719. serializationObject.visibility = this.visibility;
  22720. serializationObject.checkCollisions = this.checkCollisions;
  22721. serializationObject.isBlocker = this.isBlocker;
  22722. // Parent
  22723. if (this.parent) {
  22724. serializationObject.parentId = this.parent.id;
  22725. }
  22726. // Geometry
  22727. var geometry = this._geometry;
  22728. if (geometry) {
  22729. var geometryId = geometry.id;
  22730. serializationObject.geometryId = geometryId;
  22731. // SubMeshes
  22732. serializationObject.subMeshes = [];
  22733. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22734. var subMesh = this.subMeshes[subIndex];
  22735. serializationObject.subMeshes.push({
  22736. materialIndex: subMesh.materialIndex,
  22737. verticesStart: subMesh.verticesStart,
  22738. verticesCount: subMesh.verticesCount,
  22739. indexStart: subMesh.indexStart,
  22740. indexCount: subMesh.indexCount
  22741. });
  22742. }
  22743. }
  22744. // Material
  22745. if (this.material) {
  22746. serializationObject.materialId = this.material.id;
  22747. }
  22748. else {
  22749. this.material = null;
  22750. }
  22751. // Morph targets
  22752. if (this.morphTargetManager) {
  22753. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22754. }
  22755. // Skeleton
  22756. if (this.skeleton) {
  22757. serializationObject.skeletonId = this.skeleton.id;
  22758. }
  22759. // Physics
  22760. //TODO implement correct serialization for physics impostors.
  22761. if (this.getPhysicsImpostor()) {
  22762. var impostor = this.getPhysicsImpostor();
  22763. serializationObject.physicsMass = impostor.getParam("mass");
  22764. serializationObject.physicsFriction = impostor.getParam("friction");
  22765. serializationObject.physicsRestitution = impostor.getParam("mass");
  22766. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  22767. }
  22768. // Metadata
  22769. if (this.metadata) {
  22770. serializationObject.metadata = this.metadata;
  22771. }
  22772. // Instances
  22773. serializationObject.instances = [];
  22774. for (var index = 0; index < this.instances.length; index++) {
  22775. var instance = this.instances[index];
  22776. var serializationInstance = {
  22777. name: instance.name,
  22778. position: instance.position.asArray(),
  22779. scaling: instance.scaling.asArray()
  22780. };
  22781. if (instance.rotationQuaternion) {
  22782. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  22783. }
  22784. else if (instance.rotation) {
  22785. serializationInstance.rotation = instance.rotation.asArray();
  22786. }
  22787. serializationObject.instances.push(serializationInstance);
  22788. // Animations
  22789. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  22790. serializationInstance.ranges = instance.serializeAnimationRanges();
  22791. }
  22792. //
  22793. // Animations
  22794. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22795. serializationObject.ranges = this.serializeAnimationRanges();
  22796. // Layer mask
  22797. serializationObject.layerMask = this.layerMask;
  22798. // Alpha
  22799. serializationObject.alphaIndex = this.alphaIndex;
  22800. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  22801. // Overlay
  22802. serializationObject.overlayAlpha = this.overlayAlpha;
  22803. serializationObject.overlayColor = this.overlayColor.asArray();
  22804. serializationObject.renderOverlay = this.renderOverlay;
  22805. // Fog
  22806. serializationObject.applyFog = this.applyFog;
  22807. // Action Manager
  22808. if (this.actionManager) {
  22809. serializationObject.actions = this.actionManager.serialize(this.name);
  22810. }
  22811. };
  22812. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  22813. if (!this.geometry) {
  22814. return;
  22815. }
  22816. this._markSubMeshesAsAttributesDirty();
  22817. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  22818. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  22819. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  22820. this.morphTargetManager = undefined;
  22821. return;
  22822. }
  22823. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  22824. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  22825. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  22826. if (morphTarget.hasNormals) {
  22827. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  22828. }
  22829. if (morphTarget.hasTangents) {
  22830. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  22831. }
  22832. }
  22833. }
  22834. else {
  22835. var index = 0;
  22836. // Positions
  22837. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  22838. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  22839. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  22840. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  22841. }
  22842. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  22843. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  22844. }
  22845. index++;
  22846. }
  22847. }
  22848. };
  22849. // Statics
  22850. /**
  22851. * Returns a new Mesh object what is a deep copy of the passed mesh.
  22852. * The parameter `parsedMesh` is the mesh to be copied.
  22853. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  22854. */
  22855. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  22856. var mesh;
  22857. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  22858. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  22859. }
  22860. else {
  22861. mesh = new Mesh(parsedMesh.name, scene);
  22862. }
  22863. mesh.id = parsedMesh.id;
  22864. if (BABYLON.Tags) {
  22865. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  22866. }
  22867. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  22868. if (parsedMesh.metadata !== undefined) {
  22869. mesh.metadata = parsedMesh.metadata;
  22870. }
  22871. if (parsedMesh.rotationQuaternion) {
  22872. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  22873. }
  22874. else if (parsedMesh.rotation) {
  22875. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  22876. }
  22877. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  22878. if (parsedMesh.localMatrix) {
  22879. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  22880. }
  22881. else if (parsedMesh.pivotMatrix) {
  22882. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  22883. }
  22884. mesh.setEnabled(parsedMesh.isEnabled);
  22885. mesh.isVisible = parsedMesh.isVisible;
  22886. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  22887. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  22888. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  22889. if (parsedMesh.applyFog !== undefined) {
  22890. mesh.applyFog = parsedMesh.applyFog;
  22891. }
  22892. if (parsedMesh.pickable !== undefined) {
  22893. mesh.isPickable = parsedMesh.pickable;
  22894. }
  22895. if (parsedMesh.alphaIndex !== undefined) {
  22896. mesh.alphaIndex = parsedMesh.alphaIndex;
  22897. }
  22898. mesh.receiveShadows = parsedMesh.receiveShadows;
  22899. mesh.billboardMode = parsedMesh.billboardMode;
  22900. if (parsedMesh.visibility !== undefined) {
  22901. mesh.visibility = parsedMesh.visibility;
  22902. }
  22903. mesh.checkCollisions = parsedMesh.checkCollisions;
  22904. if (parsedMesh.isBlocker !== undefined) {
  22905. mesh.isBlocker = parsedMesh.isBlocker;
  22906. }
  22907. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  22908. // freezeWorldMatrix
  22909. if (parsedMesh.freezeWorldMatrix) {
  22910. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  22911. }
  22912. // Parent
  22913. if (parsedMesh.parentId) {
  22914. mesh._waitingParentId = parsedMesh.parentId;
  22915. }
  22916. // Actions
  22917. if (parsedMesh.actions !== undefined) {
  22918. mesh._waitingActions = parsedMesh.actions;
  22919. }
  22920. // Overlay
  22921. if (parsedMesh.overlayAlpha !== undefined) {
  22922. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  22923. }
  22924. if (parsedMesh.overlayColor !== undefined) {
  22925. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  22926. }
  22927. if (parsedMesh.renderOverlay !== undefined) {
  22928. mesh.renderOverlay = parsedMesh.renderOverlay;
  22929. }
  22930. // Geometry
  22931. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  22932. if (parsedMesh.delayLoadingFile) {
  22933. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22934. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  22935. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  22936. if (parsedMesh._binaryInfo) {
  22937. mesh._binaryInfo = parsedMesh._binaryInfo;
  22938. }
  22939. mesh._delayInfo = [];
  22940. if (parsedMesh.hasUVs) {
  22941. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  22942. }
  22943. if (parsedMesh.hasUVs2) {
  22944. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  22945. }
  22946. if (parsedMesh.hasUVs3) {
  22947. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  22948. }
  22949. if (parsedMesh.hasUVs4) {
  22950. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  22951. }
  22952. if (parsedMesh.hasUVs5) {
  22953. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  22954. }
  22955. if (parsedMesh.hasUVs6) {
  22956. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  22957. }
  22958. if (parsedMesh.hasColors) {
  22959. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  22960. }
  22961. if (parsedMesh.hasMatricesIndices) {
  22962. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22963. }
  22964. if (parsedMesh.hasMatricesWeights) {
  22965. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22966. }
  22967. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  22968. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  22969. mesh._checkDelayState();
  22970. }
  22971. }
  22972. else {
  22973. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  22974. }
  22975. // Material
  22976. if (parsedMesh.materialId) {
  22977. mesh.setMaterialByID(parsedMesh.materialId);
  22978. }
  22979. else {
  22980. mesh.material = null;
  22981. }
  22982. // Morph targets
  22983. if (parsedMesh.morphTargetManagerId > -1) {
  22984. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  22985. }
  22986. // Skeleton
  22987. if (parsedMesh.skeletonId > -1) {
  22988. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  22989. if (parsedMesh.numBoneInfluencers) {
  22990. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  22991. }
  22992. }
  22993. // Animations
  22994. if (parsedMesh.animations) {
  22995. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22996. var parsedAnimation = parsedMesh.animations[animationIndex];
  22997. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22998. }
  22999. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  23000. }
  23001. if (parsedMesh.autoAnimate) {
  23002. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  23003. }
  23004. // Layer Mask
  23005. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  23006. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  23007. }
  23008. else {
  23009. mesh.layerMask = 0x0FFFFFFF;
  23010. }
  23011. // Physics
  23012. if (parsedMesh.physicsImpostor) {
  23013. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  23014. mass: parsedMesh.physicsMass,
  23015. friction: parsedMesh.physicsFriction,
  23016. restitution: parsedMesh.physicsRestitution
  23017. }, scene);
  23018. }
  23019. // Instances
  23020. if (parsedMesh.instances) {
  23021. for (var index = 0; index < parsedMesh.instances.length; index++) {
  23022. var parsedInstance = parsedMesh.instances[index];
  23023. var instance = mesh.createInstance(parsedInstance.name);
  23024. if (BABYLON.Tags) {
  23025. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  23026. }
  23027. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  23028. if (parsedInstance.parentId) {
  23029. instance._waitingParentId = parsedInstance.parentId;
  23030. }
  23031. if (parsedInstance.rotationQuaternion) {
  23032. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  23033. }
  23034. else if (parsedInstance.rotation) {
  23035. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  23036. }
  23037. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  23038. instance.checkCollisions = mesh.checkCollisions;
  23039. if (parsedMesh.animations) {
  23040. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23041. parsedAnimation = parsedMesh.animations[animationIndex];
  23042. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23043. }
  23044. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  23045. }
  23046. }
  23047. }
  23048. return mesh;
  23049. };
  23050. /**
  23051. * Creates a ribbon mesh.
  23052. * Please consider using the same method from the MeshBuilder class instead.
  23053. * 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.
  23054. *
  23055. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23056. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23057. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23058. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23059. * 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.
  23060. * 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.
  23061. * 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
  23062. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23063. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23064. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23065. */
  23066. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  23067. return BABYLON.MeshBuilder.CreateRibbon(name, {
  23068. pathArray: pathArray,
  23069. closeArray: closeArray,
  23070. closePath: closePath,
  23071. offset: offset,
  23072. updatable: updatable,
  23073. sideOrientation: sideOrientation,
  23074. instance: instance
  23075. }, scene);
  23076. };
  23077. /**
  23078. * Creates a plane polygonal mesh. By default, this is a disc.
  23079. * Please consider using the same method from the MeshBuilder class instead.
  23080. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23081. * 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.
  23082. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23083. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23084. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23085. */
  23086. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  23087. var options = {
  23088. radius: radius,
  23089. tessellation: tessellation,
  23090. sideOrientation: sideOrientation,
  23091. updatable: updatable
  23092. };
  23093. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  23094. };
  23095. /**
  23096. * Creates a box mesh.
  23097. * Please consider using the same method from the MeshBuilder class instead.
  23098. * The parameter `size` sets the size (float) of each box side (default 1).
  23099. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23100. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23101. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23102. */
  23103. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  23104. var options = {
  23105. size: size,
  23106. sideOrientation: sideOrientation,
  23107. updatable: updatable
  23108. };
  23109. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  23110. };
  23111. /**
  23112. * Creates a sphere mesh.
  23113. * Please consider using the same method from the MeshBuilder class instead.
  23114. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  23115. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  23116. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23117. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23118. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23119. */
  23120. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  23121. var options = {
  23122. segments: segments,
  23123. diameterX: diameter,
  23124. diameterY: diameter,
  23125. diameterZ: diameter,
  23126. sideOrientation: sideOrientation,
  23127. updatable: updatable
  23128. };
  23129. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  23130. };
  23131. /**
  23132. * Creates a cylinder or a cone mesh.
  23133. * Please consider using the same method from the MeshBuilder class instead.
  23134. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23135. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23136. * 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.
  23137. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23138. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23139. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23140. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23141. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23142. */
  23143. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  23144. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  23145. if (scene !== undefined) {
  23146. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  23147. updatable = scene;
  23148. }
  23149. scene = subdivisions;
  23150. subdivisions = 1;
  23151. }
  23152. var options = {
  23153. height: height,
  23154. diameterTop: diameterTop,
  23155. diameterBottom: diameterBottom,
  23156. tessellation: tessellation,
  23157. subdivisions: subdivisions,
  23158. sideOrientation: sideOrientation,
  23159. updatable: updatable
  23160. };
  23161. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  23162. };
  23163. // Torus (Code from SharpDX.org)
  23164. /**
  23165. * Creates a torus mesh.
  23166. * Please consider using the same method from the MeshBuilder class instead.
  23167. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23168. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23169. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23170. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23171. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23172. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23173. */
  23174. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  23175. var options = {
  23176. diameter: diameter,
  23177. thickness: thickness,
  23178. tessellation: tessellation,
  23179. sideOrientation: sideOrientation,
  23180. updatable: updatable
  23181. };
  23182. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23183. };
  23184. /**
  23185. * Creates a torus knot mesh.
  23186. * Please consider using the same method from the MeshBuilder class instead.
  23187. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23188. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23189. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23190. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23191. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23192. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23193. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23194. */
  23195. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23196. var options = {
  23197. radius: radius,
  23198. tube: tube,
  23199. radialSegments: radialSegments,
  23200. tubularSegments: tubularSegments,
  23201. p: p,
  23202. q: q,
  23203. sideOrientation: sideOrientation,
  23204. updatable: updatable
  23205. };
  23206. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23207. };
  23208. /**
  23209. * Creates a line mesh.
  23210. * Please consider using the same method from the MeshBuilder class instead.
  23211. * 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.
  23212. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23213. * The parameter `points` is an array successive Vector3.
  23214. * 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
  23215. * When updating an instance, remember that only point positions can change, not the number of points.
  23216. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23217. */
  23218. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23219. var options = {
  23220. points: points,
  23221. updatable: updatable,
  23222. instance: instance
  23223. };
  23224. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23225. };
  23226. /**
  23227. * Creates a dashed line mesh.
  23228. * Please consider using the same method from the MeshBuilder class instead.
  23229. * 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.
  23230. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23231. * The parameter `points` is an array successive Vector3.
  23232. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23233. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23234. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23235. * 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
  23236. * When updating an instance, remember that only point positions can change, not the number of points.
  23237. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23238. */
  23239. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23240. var options = {
  23241. points: points,
  23242. dashSize: dashSize,
  23243. gapSize: gapSize,
  23244. dashNb: dashNb,
  23245. updatable: updatable,
  23246. instance: instance
  23247. };
  23248. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23249. };
  23250. /**
  23251. * Creates a polygon mesh.
  23252. * Please consider using the same method from the MeshBuilder class instead.
  23253. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23254. * 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.
  23255. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23256. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23257. * Remember you can only change the shape positions, not their number when updating a polygon.
  23258. */
  23259. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23260. var options = {
  23261. shape: shape,
  23262. holes: holes,
  23263. updatable: updatable,
  23264. sideOrientation: sideOrientation
  23265. };
  23266. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23267. };
  23268. /**
  23269. * Creates an extruded polygon mesh, with depth in the Y direction.
  23270. * Please consider using the same method from the MeshBuilder class instead.
  23271. */
  23272. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23273. var options = {
  23274. shape: shape,
  23275. holes: holes,
  23276. depth: depth,
  23277. updatable: updatable,
  23278. sideOrientation: sideOrientation
  23279. };
  23280. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23281. };
  23282. /**
  23283. * Creates an extruded shape mesh.
  23284. * 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.
  23285. * Please consider using the same method from the MeshBuilder class instead.
  23286. *
  23287. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23288. * 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
  23289. * extruded along the Z axis.
  23290. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23291. * 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.
  23292. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23293. * 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
  23294. * 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
  23295. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23296. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23297. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23298. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23299. */
  23300. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23301. var options = {
  23302. shape: shape,
  23303. path: path,
  23304. scale: scale,
  23305. rotation: rotation,
  23306. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23307. sideOrientation: sideOrientation,
  23308. instance: instance,
  23309. updatable: updatable
  23310. };
  23311. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23312. };
  23313. /**
  23314. * Creates an custom extruded shape mesh.
  23315. * 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.
  23316. * Please consider using the same method from the MeshBuilder class instead.
  23317. *
  23318. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23319. * 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
  23320. * extruded along the Z axis.
  23321. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23322. * 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
  23323. * and the distance of this point from the begining of the path :
  23324. * ```javascript
  23325. * var rotationFunction = function(i, distance) {
  23326. * // do things
  23327. * return rotationValue; }
  23328. * ```
  23329. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23330. * 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
  23331. * and the distance of this point from the begining of the path :
  23332. * ```javascript
  23333. * var scaleFunction = function(i, distance) {
  23334. * // do things
  23335. * return scaleValue;}
  23336. * ```
  23337. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23338. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23339. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23340. * 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
  23341. * 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
  23342. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23343. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23344. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23345. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23346. */
  23347. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23348. var options = {
  23349. shape: shape,
  23350. path: path,
  23351. scaleFunction: scaleFunction,
  23352. rotationFunction: rotationFunction,
  23353. ribbonCloseArray: ribbonCloseArray,
  23354. ribbonClosePath: ribbonClosePath,
  23355. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23356. sideOrientation: sideOrientation,
  23357. instance: instance,
  23358. updatable: updatable
  23359. };
  23360. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23361. };
  23362. /**
  23363. * Creates lathe mesh.
  23364. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23365. * Please consider using the same method from the MeshBuilder class instead.
  23366. * 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
  23367. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23368. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23369. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23370. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23371. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23372. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23373. */
  23374. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23375. var options = {
  23376. shape: shape,
  23377. radius: radius,
  23378. tessellation: tessellation,
  23379. sideOrientation: sideOrientation,
  23380. updatable: updatable
  23381. };
  23382. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23383. };
  23384. /**
  23385. * Creates a plane mesh.
  23386. * Please consider using the same method from the MeshBuilder class instead.
  23387. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23388. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23389. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23390. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23391. */
  23392. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23393. var options = {
  23394. size: size,
  23395. width: size,
  23396. height: size,
  23397. sideOrientation: sideOrientation,
  23398. updatable: updatable
  23399. };
  23400. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23401. };
  23402. /**
  23403. * Creates a ground mesh.
  23404. * Please consider using the same method from the MeshBuilder class instead.
  23405. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23406. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23407. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23408. */
  23409. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23410. var options = {
  23411. width: width,
  23412. height: height,
  23413. subdivisions: subdivisions,
  23414. updatable: updatable
  23415. };
  23416. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23417. };
  23418. /**
  23419. * Creates a tiled ground mesh.
  23420. * Please consider using the same method from the MeshBuilder class instead.
  23421. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23422. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23423. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23424. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23425. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23426. * numbers of subdivisions on the ground width and height of each tile.
  23427. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23428. */
  23429. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23430. var options = {
  23431. xmin: xmin,
  23432. zmin: zmin,
  23433. xmax: xmax,
  23434. zmax: zmax,
  23435. subdivisions: subdivisions,
  23436. precision: precision,
  23437. updatable: updatable
  23438. };
  23439. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23440. };
  23441. /**
  23442. * Creates a ground mesh from a height map.
  23443. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23444. * Please consider using the same method from the MeshBuilder class instead.
  23445. * The parameter `url` sets the URL of the height map image resource.
  23446. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23447. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23448. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23449. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23450. * 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).
  23451. * This function is passed the newly built mesh :
  23452. * ```javascript
  23453. * function(mesh) { // do things
  23454. * return; }
  23455. * ```
  23456. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23457. */
  23458. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23459. var options = {
  23460. width: width,
  23461. height: height,
  23462. subdivisions: subdivisions,
  23463. minHeight: minHeight,
  23464. maxHeight: maxHeight,
  23465. updatable: updatable,
  23466. onReady: onReady
  23467. };
  23468. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23469. };
  23470. /**
  23471. * Creates a tube mesh.
  23472. * 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.
  23473. * Please consider using the same method from the MeshBuilder class instead.
  23474. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23475. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23476. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23477. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23478. * 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.
  23479. * It must return a radius value (positive float) :
  23480. * ```javascript
  23481. * var radiusFunction = function(i, distance) {
  23482. * // do things
  23483. * return radius; }
  23484. * ```
  23485. * 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
  23486. * 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
  23487. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23488. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23489. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23490. */
  23491. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23492. var options = {
  23493. path: path,
  23494. radius: radius,
  23495. tessellation: tessellation,
  23496. radiusFunction: radiusFunction,
  23497. arc: 1,
  23498. cap: cap,
  23499. updatable: updatable,
  23500. sideOrientation: sideOrientation,
  23501. instance: instance
  23502. };
  23503. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23504. };
  23505. /**
  23506. * Creates a polyhedron mesh.
  23507. * Please consider using the same method from the MeshBuilder class instead.
  23508. * 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
  23509. * to choose the wanted type.
  23510. * The parameter `size` (positive float, default 1) sets the polygon size.
  23511. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23512. * 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`.
  23513. * 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
  23514. * 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)`).
  23515. * 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
  23516. * 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.
  23517. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23518. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23519. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23520. */
  23521. Mesh.CreatePolyhedron = function (name, options, scene) {
  23522. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23523. };
  23524. /**
  23525. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23526. * Please consider using the same method from the MeshBuilder class instead.
  23527. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23528. * 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`).
  23529. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23530. * 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.
  23531. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23532. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23534. */
  23535. Mesh.CreateIcoSphere = function (name, options, scene) {
  23536. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23537. };
  23538. /**
  23539. * Creates a decal mesh.
  23540. * Please consider using the same method from the MeshBuilder class instead.
  23541. * 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.
  23542. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23543. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23544. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23545. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23546. */
  23547. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23548. var options = {
  23549. position: position,
  23550. normal: normal,
  23551. size: size,
  23552. angle: angle
  23553. };
  23554. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23555. };
  23556. // Skeletons
  23557. /**
  23558. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23559. */
  23560. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23561. var source;
  23562. if (!this._sourcePositions) {
  23563. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23564. this._sourcePositions = new Float32Array(source);
  23565. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23566. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23567. }
  23568. }
  23569. return this._sourcePositions;
  23570. };
  23571. /**
  23572. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23573. */
  23574. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23575. var source;
  23576. if (!this._sourceNormals) {
  23577. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23578. this._sourceNormals = new Float32Array(source);
  23579. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23580. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23581. }
  23582. }
  23583. return this._sourceNormals;
  23584. };
  23585. /**
  23586. * Updates the vertex buffer by applying transformation from the bones.
  23587. * Returns the Mesh.
  23588. *
  23589. * @param {skeleton} skeleton to apply
  23590. */
  23591. Mesh.prototype.applySkeleton = function (skeleton) {
  23592. if (!this.geometry) {
  23593. return this;
  23594. }
  23595. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23596. return this;
  23597. }
  23598. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23599. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23600. return this;
  23601. }
  23602. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23603. return this;
  23604. }
  23605. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23606. return this;
  23607. }
  23608. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23609. return this;
  23610. }
  23611. if (!this._sourcePositions) {
  23612. var submeshes = this.subMeshes.slice();
  23613. this.setPositionsForCPUSkinning();
  23614. this.subMeshes = submeshes;
  23615. }
  23616. if (!this._sourceNormals) {
  23617. this.setNormalsForCPUSkinning();
  23618. }
  23619. // positionsData checks for not being Float32Array will only pass at most once
  23620. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23621. if (!(positionsData instanceof Float32Array)) {
  23622. positionsData = new Float32Array(positionsData);
  23623. }
  23624. // normalsData checks for not being Float32Array will only pass at most once
  23625. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23626. if (!(normalsData instanceof Float32Array)) {
  23627. normalsData = new Float32Array(normalsData);
  23628. }
  23629. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23630. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23631. var needExtras = this.numBoneInfluencers > 4;
  23632. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23633. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23634. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23635. var tempVector3 = BABYLON.Vector3.Zero();
  23636. var finalMatrix = new BABYLON.Matrix();
  23637. var tempMatrix = new BABYLON.Matrix();
  23638. var matWeightIdx = 0;
  23639. var inf;
  23640. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23641. var weight;
  23642. for (inf = 0; inf < 4; inf++) {
  23643. weight = matricesWeightsData[matWeightIdx + inf];
  23644. if (weight > 0) {
  23645. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23646. finalMatrix.addToSelf(tempMatrix);
  23647. }
  23648. else
  23649. break;
  23650. }
  23651. if (needExtras) {
  23652. for (inf = 0; inf < 4; inf++) {
  23653. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23654. if (weight > 0) {
  23655. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23656. finalMatrix.addToSelf(tempMatrix);
  23657. }
  23658. else
  23659. break;
  23660. }
  23661. }
  23662. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23663. tempVector3.toArray(positionsData, index);
  23664. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23665. tempVector3.toArray(normalsData, index);
  23666. finalMatrix.reset();
  23667. }
  23668. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23669. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23670. return this;
  23671. };
  23672. // Tools
  23673. /**
  23674. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23675. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23676. */
  23677. Mesh.MinMax = function (meshes) {
  23678. var minVector = null;
  23679. var maxVector = null;
  23680. meshes.forEach(function (mesh, index, array) {
  23681. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23682. if (!minVector) {
  23683. minVector = boundingBox.minimumWorld;
  23684. maxVector = boundingBox.maximumWorld;
  23685. }
  23686. else {
  23687. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23688. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23689. }
  23690. });
  23691. return {
  23692. min: minVector,
  23693. max: maxVector
  23694. };
  23695. };
  23696. /**
  23697. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23698. */
  23699. Mesh.Center = function (meshesOrMinMaxVector) {
  23700. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23701. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23702. };
  23703. /**
  23704. * Merge the array of meshes into a single mesh for performance reasons.
  23705. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23706. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23707. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23708. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23709. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23710. */
  23711. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23712. if (disposeSource === void 0) { disposeSource = true; }
  23713. var index;
  23714. if (!allow32BitsIndices) {
  23715. var totalVertices = 0;
  23716. // Counting vertices
  23717. for (index = 0; index < meshes.length; index++) {
  23718. if (meshes[index]) {
  23719. totalVertices += meshes[index].getTotalVertices();
  23720. if (totalVertices > 65536) {
  23721. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  23722. return null;
  23723. }
  23724. }
  23725. }
  23726. }
  23727. // Merge
  23728. var vertexData;
  23729. var otherVertexData;
  23730. var indiceArray = new Array();
  23731. var source;
  23732. for (index = 0; index < meshes.length; index++) {
  23733. if (meshes[index]) {
  23734. meshes[index].computeWorldMatrix(true);
  23735. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23736. otherVertexData.transform(meshes[index].getWorldMatrix());
  23737. if (vertexData) {
  23738. vertexData.merge(otherVertexData);
  23739. }
  23740. else {
  23741. vertexData = otherVertexData;
  23742. source = meshes[index];
  23743. }
  23744. if (subdivideWithSubMeshes) {
  23745. indiceArray.push(meshes[index].getTotalIndices());
  23746. }
  23747. }
  23748. }
  23749. if (!meshSubclass) {
  23750. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23751. }
  23752. vertexData.applyToMesh(meshSubclass);
  23753. // Setting properties
  23754. meshSubclass.material = source.material;
  23755. meshSubclass.checkCollisions = source.checkCollisions;
  23756. // Cleaning
  23757. if (disposeSource) {
  23758. for (index = 0; index < meshes.length; index++) {
  23759. if (meshes[index]) {
  23760. meshes[index].dispose();
  23761. }
  23762. }
  23763. }
  23764. // Subdivide
  23765. if (subdivideWithSubMeshes) {
  23766. //-- Suppresions du submesh global
  23767. meshSubclass.releaseSubMeshes();
  23768. index = 0;
  23769. var offset = 0;
  23770. //-- aplique la subdivision en fonction du tableau d'indices
  23771. while (index < indiceArray.length) {
  23772. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  23773. offset += indiceArray[index];
  23774. index++;
  23775. }
  23776. }
  23777. return meshSubclass;
  23778. };
  23779. // Consts
  23780. Mesh._FRONTSIDE = 0;
  23781. Mesh._BACKSIDE = 1;
  23782. Mesh._DOUBLESIDE = 2;
  23783. Mesh._DEFAULTSIDE = 0;
  23784. Mesh._NO_CAP = 0;
  23785. Mesh._CAP_START = 1;
  23786. Mesh._CAP_END = 2;
  23787. Mesh._CAP_ALL = 3;
  23788. return Mesh;
  23789. }(BABYLON.AbstractMesh));
  23790. BABYLON.Mesh = Mesh;
  23791. })(BABYLON || (BABYLON = {}));
  23792. //# sourceMappingURL=babylon.mesh.js.map
  23793. var BABYLON;
  23794. (function (BABYLON) {
  23795. var BaseSubMesh = (function () {
  23796. function BaseSubMesh() {
  23797. }
  23798. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  23799. get: function () {
  23800. return this._materialEffect;
  23801. },
  23802. enumerable: true,
  23803. configurable: true
  23804. });
  23805. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  23806. if (this._materialEffect === effect) {
  23807. if (!effect) {
  23808. this._materialDefines = undefined;
  23809. }
  23810. return;
  23811. }
  23812. this._materialDefines = defines;
  23813. this._materialEffect = effect;
  23814. };
  23815. return BaseSubMesh;
  23816. }());
  23817. BABYLON.BaseSubMesh = BaseSubMesh;
  23818. var SubMesh = (function (_super) {
  23819. __extends(SubMesh, _super);
  23820. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  23821. if (createBoundingBox === void 0) { createBoundingBox = true; }
  23822. var _this = _super.call(this) || this;
  23823. _this.materialIndex = materialIndex;
  23824. _this.verticesStart = verticesStart;
  23825. _this.verticesCount = verticesCount;
  23826. _this.indexStart = indexStart;
  23827. _this.indexCount = indexCount;
  23828. _this._renderId = 0;
  23829. _this._mesh = mesh;
  23830. _this._renderingMesh = renderingMesh || mesh;
  23831. mesh.subMeshes.push(_this);
  23832. _this._trianglePlanes = [];
  23833. _this._id = mesh.subMeshes.length - 1;
  23834. if (createBoundingBox) {
  23835. _this.refreshBoundingInfo();
  23836. mesh.computeWorldMatrix(true);
  23837. }
  23838. return _this;
  23839. }
  23840. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  23841. get: function () {
  23842. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  23843. },
  23844. enumerable: true,
  23845. configurable: true
  23846. });
  23847. /**
  23848. * Returns the submesh BoudingInfo object.
  23849. */
  23850. SubMesh.prototype.getBoundingInfo = function () {
  23851. if (this.IsGlobal) {
  23852. return this._mesh.getBoundingInfo();
  23853. }
  23854. return this._boundingInfo;
  23855. };
  23856. /**
  23857. * Sets the submesh BoundingInfo.
  23858. * Return the SubMesh.
  23859. */
  23860. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  23861. this._boundingInfo = boundingInfo;
  23862. return this;
  23863. };
  23864. /**
  23865. * Returns the mesh of the current submesh.
  23866. */
  23867. SubMesh.prototype.getMesh = function () {
  23868. return this._mesh;
  23869. };
  23870. /**
  23871. * Returns the rendering mesh of the submesh.
  23872. */
  23873. SubMesh.prototype.getRenderingMesh = function () {
  23874. return this._renderingMesh;
  23875. };
  23876. /**
  23877. * Returns the submesh material.
  23878. */
  23879. SubMesh.prototype.getMaterial = function () {
  23880. var rootMaterial = this._renderingMesh.material;
  23881. if (rootMaterial && rootMaterial.getSubMaterial) {
  23882. var multiMaterial = rootMaterial;
  23883. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  23884. if (this._currentMaterial !== effectiveMaterial) {
  23885. this._currentMaterial = effectiveMaterial;
  23886. this._materialDefines = undefined;
  23887. }
  23888. return effectiveMaterial;
  23889. }
  23890. if (!rootMaterial) {
  23891. return this._mesh.getScene().defaultMaterial;
  23892. }
  23893. return rootMaterial;
  23894. };
  23895. // Methods
  23896. /**
  23897. * Sets a new updated BoundingInfo object to the submesh.
  23898. * Returns the SubMesh.
  23899. */
  23900. SubMesh.prototype.refreshBoundingInfo = function () {
  23901. this._lastColliderWorldVertices = null;
  23902. if (this.IsGlobal) {
  23903. return;
  23904. }
  23905. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23906. if (!data) {
  23907. this._boundingInfo = this._mesh._boundingInfo;
  23908. return;
  23909. }
  23910. var indices = this._renderingMesh.getIndices();
  23911. var extend;
  23912. //is this the only submesh?
  23913. if (this.indexStart === 0 && this.indexCount === indices.length) {
  23914. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  23915. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  23916. }
  23917. else {
  23918. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  23919. }
  23920. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23921. return this;
  23922. };
  23923. SubMesh.prototype._checkCollision = function (collider) {
  23924. return this.getBoundingInfo()._checkCollision(collider);
  23925. };
  23926. /**
  23927. * Updates the submesh BoundingInfo.
  23928. * Returns the Submesh.
  23929. */
  23930. SubMesh.prototype.updateBoundingInfo = function (world) {
  23931. if (!this.getBoundingInfo()) {
  23932. this.refreshBoundingInfo();
  23933. }
  23934. this.getBoundingInfo().update(world);
  23935. return this;
  23936. };
  23937. /**
  23938. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  23939. * Boolean returned.
  23940. */
  23941. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  23942. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  23943. };
  23944. /**
  23945. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  23946. * Boolean returned.
  23947. */
  23948. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  23949. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  23950. };
  23951. /**
  23952. * Renders the submesh.
  23953. * Returns it.
  23954. */
  23955. SubMesh.prototype.render = function (enableAlphaMode) {
  23956. this._renderingMesh.render(this, enableAlphaMode);
  23957. return this;
  23958. };
  23959. /**
  23960. * Returns a new Index Buffer.
  23961. * Type returned : WebGLBuffer.
  23962. */
  23963. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  23964. if (!this._linesIndexBuffer) {
  23965. var linesIndices = [];
  23966. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23967. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  23968. }
  23969. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  23970. this.linesIndexCount = linesIndices.length;
  23971. }
  23972. return this._linesIndexBuffer;
  23973. };
  23974. /**
  23975. * True is the passed Ray intersects the submesh bounding box.
  23976. * Boolean returned.
  23977. */
  23978. SubMesh.prototype.canIntersects = function (ray) {
  23979. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  23980. };
  23981. /**
  23982. * Returns an object IntersectionInfo.
  23983. */
  23984. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  23985. var intersectInfo = null;
  23986. // LineMesh first as it's also a Mesh...
  23987. if (this._mesh instanceof BABYLON.LinesMesh) {
  23988. var lineMesh = this._mesh;
  23989. // Line test
  23990. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  23991. var p0 = positions[indices[index]];
  23992. var p1 = positions[indices[index + 1]];
  23993. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  23994. if (length < 0) {
  23995. continue;
  23996. }
  23997. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  23998. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  23999. if (fastCheck) {
  24000. break;
  24001. }
  24002. }
  24003. }
  24004. }
  24005. else {
  24006. // Triangles test
  24007. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24008. var p0 = positions[indices[index]];
  24009. var p1 = positions[indices[index + 1]];
  24010. var p2 = positions[indices[index + 2]];
  24011. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24012. if (currentIntersectInfo) {
  24013. if (currentIntersectInfo.distance < 0) {
  24014. continue;
  24015. }
  24016. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24017. intersectInfo = currentIntersectInfo;
  24018. intersectInfo.faceId = index / 3;
  24019. if (fastCheck) {
  24020. break;
  24021. }
  24022. }
  24023. }
  24024. }
  24025. }
  24026. return intersectInfo;
  24027. };
  24028. SubMesh.prototype._rebuild = function () {
  24029. if (this._linesIndexBuffer) {
  24030. this._linesIndexBuffer = null;
  24031. }
  24032. };
  24033. // Clone
  24034. /**
  24035. * Creates a new Submesh from the passed Mesh.
  24036. */
  24037. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24038. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24039. if (!this.IsGlobal) {
  24040. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  24041. }
  24042. return result;
  24043. };
  24044. // Dispose
  24045. /**
  24046. * Disposes the Submesh.
  24047. * Returns nothing.
  24048. */
  24049. SubMesh.prototype.dispose = function () {
  24050. if (this._linesIndexBuffer) {
  24051. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  24052. this._linesIndexBuffer = null;
  24053. }
  24054. // Remove from mesh
  24055. var index = this._mesh.subMeshes.indexOf(this);
  24056. this._mesh.subMeshes.splice(index, 1);
  24057. };
  24058. // Statics
  24059. /**
  24060. * Creates a new Submesh from the passed parameters :
  24061. * - materialIndex (integer) : the index of the main mesh material.
  24062. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  24063. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  24064. * - mesh (Mesh) : the main mesh to create the submesh from.
  24065. * - renderingMesh (optional Mesh) : rendering mesh.
  24066. */
  24067. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  24068. var minVertexIndex = Number.MAX_VALUE;
  24069. var maxVertexIndex = -Number.MAX_VALUE;
  24070. renderingMesh = renderingMesh || mesh;
  24071. var indices = renderingMesh.getIndices();
  24072. for (var index = startIndex; index < startIndex + indexCount; index++) {
  24073. var vertexIndex = indices[index];
  24074. if (vertexIndex < minVertexIndex)
  24075. minVertexIndex = vertexIndex;
  24076. if (vertexIndex > maxVertexIndex)
  24077. maxVertexIndex = vertexIndex;
  24078. }
  24079. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  24080. };
  24081. return SubMesh;
  24082. }(BaseSubMesh));
  24083. BABYLON.SubMesh = SubMesh;
  24084. })(BABYLON || (BABYLON = {}));
  24085. //# sourceMappingURL=babylon.subMesh.js.map
  24086. var BABYLON;
  24087. (function (BABYLON) {
  24088. var EffectFallbacks = (function () {
  24089. function EffectFallbacks() {
  24090. this._defines = {};
  24091. this._currentRank = 32;
  24092. this._maxRank = -1;
  24093. }
  24094. EffectFallbacks.prototype.unBindMesh = function () {
  24095. this._mesh = null;
  24096. };
  24097. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24098. if (!this._defines[rank]) {
  24099. if (rank < this._currentRank) {
  24100. this._currentRank = rank;
  24101. }
  24102. if (rank > this._maxRank) {
  24103. this._maxRank = rank;
  24104. }
  24105. this._defines[rank] = new Array();
  24106. }
  24107. this._defines[rank].push(define);
  24108. };
  24109. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24110. this._meshRank = rank;
  24111. this._mesh = mesh;
  24112. if (rank < this._currentRank) {
  24113. this._currentRank = rank;
  24114. }
  24115. if (rank > this._maxRank) {
  24116. this._maxRank = rank;
  24117. }
  24118. };
  24119. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24120. get: function () {
  24121. return this._currentRank <= this._maxRank;
  24122. },
  24123. enumerable: true,
  24124. configurable: true
  24125. });
  24126. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24127. // First we try to switch to CPU skinning
  24128. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  24129. this._mesh.computeBonesUsingShaders = false;
  24130. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24131. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24132. var scene = this._mesh.getScene();
  24133. for (var index = 0; index < scene.meshes.length; index++) {
  24134. var otherMesh = scene.meshes[index];
  24135. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  24136. otherMesh.computeBonesUsingShaders = false;
  24137. }
  24138. }
  24139. }
  24140. else {
  24141. var currentFallbacks = this._defines[this._currentRank];
  24142. if (currentFallbacks) {
  24143. for (var index = 0; index < currentFallbacks.length; index++) {
  24144. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24145. }
  24146. }
  24147. this._currentRank++;
  24148. }
  24149. return currentDefines;
  24150. };
  24151. return EffectFallbacks;
  24152. }());
  24153. BABYLON.EffectFallbacks = EffectFallbacks;
  24154. var EffectCreationOptions = (function () {
  24155. function EffectCreationOptions() {
  24156. }
  24157. return EffectCreationOptions;
  24158. }());
  24159. BABYLON.EffectCreationOptions = EffectCreationOptions;
  24160. var Effect = (function () {
  24161. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24162. var _this = this;
  24163. this.uniqueId = 0;
  24164. this.onCompileObservable = new BABYLON.Observable();
  24165. this.onErrorObservable = new BABYLON.Observable();
  24166. this.onBindObservable = new BABYLON.Observable();
  24167. this._uniformBuffersNames = {};
  24168. this._isReady = false;
  24169. this._compilationError = "";
  24170. this.name = baseName;
  24171. if (attributesNamesOrOptions.attributes) {
  24172. var options = attributesNamesOrOptions;
  24173. this._engine = uniformsNamesOrEngine;
  24174. this._attributesNames = options.attributes;
  24175. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24176. this._samplers = options.samplers;
  24177. this.defines = options.defines;
  24178. this.onError = options.onError;
  24179. this.onCompiled = options.onCompiled;
  24180. this._fallbacks = options.fallbacks;
  24181. this._indexParameters = options.indexParameters;
  24182. if (options.uniformBuffersNames) {
  24183. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24184. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24185. }
  24186. }
  24187. }
  24188. else {
  24189. this._engine = engine;
  24190. this.defines = defines;
  24191. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24192. this._samplers = samplers;
  24193. this._attributesNames = attributesNamesOrOptions;
  24194. this.onError = onError;
  24195. this.onCompiled = onCompiled;
  24196. this._indexParameters = indexParameters;
  24197. this._fallbacks = fallbacks;
  24198. }
  24199. this.uniqueId = Effect._uniqueIdSeed++;
  24200. var vertexSource;
  24201. var fragmentSource;
  24202. if (baseName.vertexElement) {
  24203. vertexSource = document.getElementById(baseName.vertexElement);
  24204. if (!vertexSource) {
  24205. vertexSource = baseName.vertexElement;
  24206. }
  24207. }
  24208. else {
  24209. vertexSource = baseName.vertex || baseName;
  24210. }
  24211. if (baseName.fragmentElement) {
  24212. fragmentSource = document.getElementById(baseName.fragmentElement);
  24213. if (!fragmentSource) {
  24214. fragmentSource = baseName.fragmentElement;
  24215. }
  24216. }
  24217. else {
  24218. fragmentSource = baseName.fragment || baseName;
  24219. }
  24220. this._loadVertexShader(vertexSource, function (vertexCode) {
  24221. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24222. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24223. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24224. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24225. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24226. if (baseName) {
  24227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + migratedVertexCode;
  24228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + migratedFragmentCode;
  24229. }
  24230. else {
  24231. _this._vertexSourceCode = migratedVertexCode;
  24232. _this._fragmentSourceCode = migratedFragmentCode;
  24233. }
  24234. _this._prepareEffect();
  24235. });
  24236. });
  24237. });
  24238. });
  24239. });
  24240. });
  24241. }
  24242. Object.defineProperty(Effect.prototype, "key", {
  24243. get: function () {
  24244. return this._key;
  24245. },
  24246. enumerable: true,
  24247. configurable: true
  24248. });
  24249. // Properties
  24250. Effect.prototype.isReady = function () {
  24251. return this._isReady;
  24252. };
  24253. Effect.prototype.getEngine = function () {
  24254. return this._engine;
  24255. };
  24256. Effect.prototype.getProgram = function () {
  24257. return this._program;
  24258. };
  24259. Effect.prototype.getAttributesNames = function () {
  24260. return this._attributesNames;
  24261. };
  24262. Effect.prototype.getAttributeLocation = function (index) {
  24263. return this._attributes[index];
  24264. };
  24265. Effect.prototype.getAttributeLocationByName = function (name) {
  24266. var index = this._attributesNames.indexOf(name);
  24267. return this._attributes[index];
  24268. };
  24269. Effect.prototype.getAttributesCount = function () {
  24270. return this._attributes.length;
  24271. };
  24272. Effect.prototype.getUniformIndex = function (uniformName) {
  24273. return this._uniformsNames.indexOf(uniformName);
  24274. };
  24275. Effect.prototype.getUniform = function (uniformName) {
  24276. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24277. };
  24278. Effect.prototype.getSamplers = function () {
  24279. return this._samplers;
  24280. };
  24281. Effect.prototype.getCompilationError = function () {
  24282. return this._compilationError;
  24283. };
  24284. // Methods
  24285. Effect.prototype.executeWhenCompiled = function (func) {
  24286. if (this.isReady()) {
  24287. func(this);
  24288. return;
  24289. }
  24290. this.onCompileObservable.add(function (effect) {
  24291. func(effect);
  24292. });
  24293. };
  24294. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24295. // DOM element ?
  24296. if (vertex instanceof HTMLElement) {
  24297. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24298. callback(vertexCode);
  24299. return;
  24300. }
  24301. // Base64 encoded ?
  24302. if (vertex.substr(0, 7) === "base64:") {
  24303. var vertexBinary = window.atob(vertex.substr(7));
  24304. callback(vertexBinary);
  24305. return;
  24306. }
  24307. // Is in local store ?
  24308. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24309. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24310. return;
  24311. }
  24312. var vertexShaderUrl;
  24313. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24314. vertexShaderUrl = vertex;
  24315. }
  24316. else {
  24317. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24318. }
  24319. // Vertex shader
  24320. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24321. };
  24322. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24323. // DOM element ?
  24324. if (fragment instanceof HTMLElement) {
  24325. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24326. callback(fragmentCode);
  24327. return;
  24328. }
  24329. // Base64 encoded ?
  24330. if (fragment.substr(0, 7) === "base64:") {
  24331. var fragmentBinary = window.atob(fragment.substr(7));
  24332. callback(fragmentBinary);
  24333. return;
  24334. }
  24335. // Is in local store ?
  24336. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24337. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24338. return;
  24339. }
  24340. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24341. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24342. return;
  24343. }
  24344. var fragmentShaderUrl;
  24345. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24346. fragmentShaderUrl = fragment;
  24347. }
  24348. else {
  24349. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24350. }
  24351. // Fragment shader
  24352. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24353. };
  24354. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24355. // Rebuild shaders source code
  24356. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24357. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24358. vertexCode = prefix + vertexCode;
  24359. fragmentCode = prefix + fragmentCode;
  24360. // Number lines of shaders source code
  24361. var i = 2;
  24362. var regex = /\n/gm;
  24363. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24364. i = 2;
  24365. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24366. // Dump shaders name and formatted source code
  24367. if (this.name.vertexElement) {
  24368. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24369. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24370. }
  24371. else if (this.name.vertex) {
  24372. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24373. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24374. }
  24375. else {
  24376. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24377. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24378. }
  24379. };
  24380. ;
  24381. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24382. var preparedSourceCode = this._processPrecision(sourceCode);
  24383. if (this._engine.webGLVersion == 1) {
  24384. callback(preparedSourceCode);
  24385. return;
  24386. }
  24387. // Already converted
  24388. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24389. callback(preparedSourceCode.replace("#version 300 es", ""));
  24390. return;
  24391. }
  24392. // Remove extensions
  24393. // #extension GL_OES_standard_derivatives : enable
  24394. // #extension GL_EXT_shader_texture_lod : enable
  24395. // #extension GL_EXT_frag_depth : enable
  24396. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  24397. var result = preparedSourceCode.replace(regex, "");
  24398. // Migrate to GLSL v300
  24399. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24400. result = result.replace(/attribute[ \t]/g, "in ");
  24401. result = result.replace(/[ \t]attribute/g, " in");
  24402. if (isFragment) {
  24403. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  24404. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  24405. result = result.replace(/texture2D\(/g, "texture(");
  24406. result = result.replace(/textureCube\(/g, "texture(");
  24407. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24408. result = result.replace(/gl_FragColor/g, "glFragColor");
  24409. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  24410. }
  24411. callback(result);
  24412. };
  24413. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24414. var _this = this;
  24415. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24416. var match = regex.exec(sourceCode);
  24417. var returnValue = new String(sourceCode);
  24418. while (match != null) {
  24419. var includeFile = match[1];
  24420. // Uniform declaration
  24421. if (includeFile.indexOf("__decl__") !== -1) {
  24422. includeFile = includeFile.replace(/__decl__/, "");
  24423. if (this._engine.supportsUniformBuffers) {
  24424. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24425. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24426. }
  24427. includeFile = includeFile + "Declaration";
  24428. }
  24429. if (Effect.IncludesShadersStore[includeFile]) {
  24430. // Substitution
  24431. var includeContent = Effect.IncludesShadersStore[includeFile];
  24432. if (match[2]) {
  24433. var splits = match[3].split(",");
  24434. for (var index = 0; index < splits.length; index += 2) {
  24435. var source = new RegExp(splits[index], "g");
  24436. var dest = splits[index + 1];
  24437. includeContent = includeContent.replace(source, dest);
  24438. }
  24439. }
  24440. if (match[4]) {
  24441. var indexString = match[5];
  24442. if (indexString.indexOf("..") !== -1) {
  24443. var indexSplits = indexString.split("..");
  24444. var minIndex = parseInt(indexSplits[0]);
  24445. var maxIndex = parseInt(indexSplits[1]);
  24446. var sourceIncludeContent = includeContent.slice(0);
  24447. includeContent = "";
  24448. if (isNaN(maxIndex)) {
  24449. maxIndex = this._indexParameters[indexSplits[1]];
  24450. }
  24451. for (var i = minIndex; i < maxIndex; i++) {
  24452. if (!this._engine.supportsUniformBuffers) {
  24453. // Ubo replacement
  24454. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24455. return p1 + "{X}";
  24456. });
  24457. }
  24458. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24459. }
  24460. }
  24461. else {
  24462. if (!this._engine.supportsUniformBuffers) {
  24463. // Ubo replacement
  24464. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24465. return p1 + "{X}";
  24466. });
  24467. }
  24468. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24469. }
  24470. }
  24471. // Replace
  24472. returnValue = returnValue.replace(match[0], includeContent);
  24473. }
  24474. else {
  24475. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24476. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24477. Effect.IncludesShadersStore[includeFile] = fileContent;
  24478. _this._processIncludes(returnValue, callback);
  24479. });
  24480. return;
  24481. }
  24482. match = regex.exec(sourceCode);
  24483. }
  24484. callback(returnValue);
  24485. };
  24486. Effect.prototype._processPrecision = function (source) {
  24487. if (source.indexOf("precision highp float") === -1) {
  24488. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24489. source = "precision mediump float;\n" + source;
  24490. }
  24491. else {
  24492. source = "precision highp float;\n" + source;
  24493. }
  24494. }
  24495. else {
  24496. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24497. source = source.replace("precision highp float", "precision mediump float");
  24498. }
  24499. }
  24500. return source;
  24501. };
  24502. Effect.prototype._prepareEffect = function () {
  24503. var attributesNames = this._attributesNames;
  24504. var defines = this.defines;
  24505. var fallbacks = this._fallbacks;
  24506. this._valueCache = {};
  24507. try {
  24508. var engine = this._engine;
  24509. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24510. if (engine.webGLVersion > 1) {
  24511. for (var name in this._uniformBuffersNames) {
  24512. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24513. }
  24514. }
  24515. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24516. this._attributes = engine.getAttributes(this._program, attributesNames);
  24517. var index;
  24518. for (index = 0; index < this._samplers.length; index++) {
  24519. var sampler = this.getUniform(this._samplers[index]);
  24520. if (sampler == null) {
  24521. this._samplers.splice(index, 1);
  24522. index--;
  24523. }
  24524. }
  24525. engine.bindSamplers(this);
  24526. this._compilationError = "";
  24527. this._isReady = true;
  24528. if (this.onCompiled) {
  24529. this.onCompiled(this);
  24530. }
  24531. this.onCompileObservable.notifyObservers(this);
  24532. this.onCompileObservable.clear();
  24533. // Unbind mesh reference in fallbacks
  24534. if (this._fallbacks) {
  24535. this._fallbacks.unBindMesh();
  24536. }
  24537. }
  24538. catch (e) {
  24539. this._compilationError = e.message;
  24540. // Let's go through fallbacks then
  24541. BABYLON.Tools.Error("Unable to compile effect:");
  24542. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24543. return " " + uniform;
  24544. }));
  24545. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24546. return " " + attribute;
  24547. }));
  24548. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24549. BABYLON.Tools.Error("Error: " + this._compilationError);
  24550. if (fallbacks && fallbacks.isMoreFallbacks) {
  24551. BABYLON.Tools.Error("Trying next fallback.");
  24552. this.defines = fallbacks.reduce(this.defines);
  24553. this._prepareEffect();
  24554. }
  24555. else {
  24556. if (this.onError) {
  24557. this.onError(this, this._compilationError);
  24558. }
  24559. this.onErrorObservable.notifyObservers(this);
  24560. this.onErrorObservable.clear();
  24561. // Unbind mesh reference in fallbacks
  24562. if (this._fallbacks) {
  24563. this._fallbacks.unBindMesh();
  24564. }
  24565. }
  24566. }
  24567. };
  24568. Object.defineProperty(Effect.prototype, "isSupported", {
  24569. get: function () {
  24570. return this._compilationError === "";
  24571. },
  24572. enumerable: true,
  24573. configurable: true
  24574. });
  24575. Effect.prototype._bindTexture = function (channel, texture) {
  24576. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24577. };
  24578. Effect.prototype.setTexture = function (channel, texture) {
  24579. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24580. };
  24581. Effect.prototype.setTextureArray = function (channel, textures) {
  24582. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24583. var initialPos = this._samplers.indexOf(channel);
  24584. for (var index = 1; index < textures.length; index++) {
  24585. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24586. }
  24587. }
  24588. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24589. };
  24590. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24591. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24592. };
  24593. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24594. var cache = this._valueCache[uniformName];
  24595. var flag = matrix.updateFlag;
  24596. if (cache !== undefined && cache === flag) {
  24597. return false;
  24598. }
  24599. this._valueCache[uniformName] = flag;
  24600. return true;
  24601. };
  24602. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24603. var cache = this._valueCache[uniformName];
  24604. if (!cache) {
  24605. cache = [x, y];
  24606. this._valueCache[uniformName] = cache;
  24607. return true;
  24608. }
  24609. var changed = false;
  24610. if (cache[0] !== x) {
  24611. cache[0] = x;
  24612. changed = true;
  24613. }
  24614. if (cache[1] !== y) {
  24615. cache[1] = y;
  24616. changed = true;
  24617. }
  24618. return changed;
  24619. };
  24620. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24621. var cache = this._valueCache[uniformName];
  24622. if (!cache) {
  24623. cache = [x, y, z];
  24624. this._valueCache[uniformName] = cache;
  24625. return true;
  24626. }
  24627. var changed = false;
  24628. if (cache[0] !== x) {
  24629. cache[0] = x;
  24630. changed = true;
  24631. }
  24632. if (cache[1] !== y) {
  24633. cache[1] = y;
  24634. changed = true;
  24635. }
  24636. if (cache[2] !== z) {
  24637. cache[2] = z;
  24638. changed = true;
  24639. }
  24640. return changed;
  24641. };
  24642. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24643. var cache = this._valueCache[uniformName];
  24644. if (!cache) {
  24645. cache = [x, y, z, w];
  24646. this._valueCache[uniformName] = cache;
  24647. return true;
  24648. }
  24649. var changed = false;
  24650. if (cache[0] !== x) {
  24651. cache[0] = x;
  24652. changed = true;
  24653. }
  24654. if (cache[1] !== y) {
  24655. cache[1] = y;
  24656. changed = true;
  24657. }
  24658. if (cache[2] !== z) {
  24659. cache[2] = z;
  24660. changed = true;
  24661. }
  24662. if (cache[3] !== w) {
  24663. cache[3] = w;
  24664. changed = true;
  24665. }
  24666. return changed;
  24667. };
  24668. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  24669. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  24670. return;
  24671. }
  24672. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  24673. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  24674. };
  24675. Effect.prototype.bindUniformBlock = function (blockName, index) {
  24676. this._engine.bindUniformBlock(this._program, blockName, index);
  24677. };
  24678. Effect.prototype.setIntArray = function (uniformName, array) {
  24679. this._valueCache[uniformName] = null;
  24680. this._engine.setIntArray(this.getUniform(uniformName), array);
  24681. return this;
  24682. };
  24683. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24684. this._valueCache[uniformName] = null;
  24685. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24686. return this;
  24687. };
  24688. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24689. this._valueCache[uniformName] = null;
  24690. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24691. return this;
  24692. };
  24693. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24694. this._valueCache[uniformName] = null;
  24695. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24696. return this;
  24697. };
  24698. Effect.prototype.setFloatArray = function (uniformName, array) {
  24699. this._valueCache[uniformName] = null;
  24700. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24701. return this;
  24702. };
  24703. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24704. this._valueCache[uniformName] = null;
  24705. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24706. return this;
  24707. };
  24708. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24709. this._valueCache[uniformName] = null;
  24710. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24711. return this;
  24712. };
  24713. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24714. this._valueCache[uniformName] = null;
  24715. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24716. return this;
  24717. };
  24718. Effect.prototype.setArray = function (uniformName, array) {
  24719. this._valueCache[uniformName] = null;
  24720. this._engine.setArray(this.getUniform(uniformName), array);
  24721. return this;
  24722. };
  24723. Effect.prototype.setArray2 = function (uniformName, array) {
  24724. this._valueCache[uniformName] = null;
  24725. this._engine.setArray2(this.getUniform(uniformName), array);
  24726. return this;
  24727. };
  24728. Effect.prototype.setArray3 = function (uniformName, array) {
  24729. this._valueCache[uniformName] = null;
  24730. this._engine.setArray3(this.getUniform(uniformName), array);
  24731. return this;
  24732. };
  24733. Effect.prototype.setArray4 = function (uniformName, array) {
  24734. this._valueCache[uniformName] = null;
  24735. this._engine.setArray4(this.getUniform(uniformName), array);
  24736. return this;
  24737. };
  24738. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24739. if (!matrices) {
  24740. return;
  24741. }
  24742. this._valueCache[uniformName] = null;
  24743. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24744. return this;
  24745. };
  24746. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24747. if (this._cacheMatrix(uniformName, matrix)) {
  24748. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24749. }
  24750. return this;
  24751. };
  24752. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24753. this._valueCache[uniformName] = null;
  24754. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24755. return this;
  24756. };
  24757. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24758. this._valueCache[uniformName] = null;
  24759. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24760. return this;
  24761. };
  24762. Effect.prototype.setFloat = function (uniformName, value) {
  24763. var cache = this._valueCache[uniformName];
  24764. if (cache !== undefined && cache === value)
  24765. return this;
  24766. this._valueCache[uniformName] = value;
  24767. this._engine.setFloat(this.getUniform(uniformName), value);
  24768. return this;
  24769. };
  24770. Effect.prototype.setBool = function (uniformName, bool) {
  24771. var cache = this._valueCache[uniformName];
  24772. if (cache !== undefined && cache === bool)
  24773. return this;
  24774. this._valueCache[uniformName] = bool;
  24775. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24776. return this;
  24777. };
  24778. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24779. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24780. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24781. }
  24782. return this;
  24783. };
  24784. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24785. if (this._cacheFloat2(uniformName, x, y)) {
  24786. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24787. }
  24788. return this;
  24789. };
  24790. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24791. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24792. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24793. }
  24794. return this;
  24795. };
  24796. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24797. if (this._cacheFloat3(uniformName, x, y, z)) {
  24798. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24799. }
  24800. return this;
  24801. };
  24802. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24803. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24804. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24805. }
  24806. return this;
  24807. };
  24808. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24809. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24810. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24811. }
  24812. return this;
  24813. };
  24814. Effect.prototype.setColor3 = function (uniformName, color3) {
  24815. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24816. this._engine.setColor3(this.getUniform(uniformName), color3);
  24817. }
  24818. return this;
  24819. };
  24820. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24821. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24822. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24823. }
  24824. return this;
  24825. };
  24826. Effect.ResetCache = function () {
  24827. Effect._baseCache = {};
  24828. };
  24829. Effect._uniqueIdSeed = 0;
  24830. Effect._baseCache = {};
  24831. // Statics
  24832. Effect.ShadersStore = {};
  24833. Effect.IncludesShadersStore = {};
  24834. return Effect;
  24835. }());
  24836. BABYLON.Effect = Effect;
  24837. })(BABYLON || (BABYLON = {}));
  24838. //# sourceMappingURL=babylon.effect.js.map
  24839. var BABYLON;
  24840. (function (BABYLON) {
  24841. var MaterialHelper = (function () {
  24842. function MaterialHelper() {
  24843. }
  24844. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  24845. defines._needUVs = true;
  24846. defines[key] = true;
  24847. if (texture.getTextureMatrix().isIdentity(true)) {
  24848. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  24849. if (texture.coordinatesIndex === 0) {
  24850. defines["MAINUV1"] = true;
  24851. }
  24852. else {
  24853. defines["MAINUV2"] = true;
  24854. }
  24855. }
  24856. else {
  24857. defines[key + "DIRECTUV"] = 0;
  24858. }
  24859. };
  24860. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  24861. var matrix = texture.getTextureMatrix();
  24862. if (!matrix.isIdentity(true)) {
  24863. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  24864. }
  24865. };
  24866. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  24867. if (defines._areMiscDirty) {
  24868. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  24869. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  24870. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  24871. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  24872. }
  24873. };
  24874. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  24875. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  24876. var changed = false;
  24877. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  24878. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  24879. changed = true;
  24880. }
  24881. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  24882. defines["ALPHATEST"] = !defines["ALPHATEST"];
  24883. changed = true;
  24884. }
  24885. if (defines["INSTANCES"] !== useInstances) {
  24886. defines["INSTANCES"] = useInstances;
  24887. changed = true;
  24888. }
  24889. if (changed) {
  24890. defines.markAsUnprocessed();
  24891. }
  24892. };
  24893. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  24894. if (useMorphTargets === void 0) { useMorphTargets = false; }
  24895. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  24896. return false;
  24897. }
  24898. defines._normals = defines._needNormals;
  24899. defines._uvs = defines._needUVs;
  24900. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  24901. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24902. defines["TANGENT"] = true;
  24903. }
  24904. if (defines._needUVs) {
  24905. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  24906. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  24907. }
  24908. else {
  24909. defines["UV1"] = false;
  24910. defines["UV2"] = false;
  24911. }
  24912. if (useVertexColor) {
  24913. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  24914. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  24915. }
  24916. if (useBones) {
  24917. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24918. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  24919. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  24920. }
  24921. else {
  24922. defines["NUM_BONE_INFLUENCERS"] = 0;
  24923. defines["BonesPerMesh"] = 0;
  24924. }
  24925. }
  24926. if (useMorphTargets) {
  24927. if (mesh.morphTargetManager) {
  24928. var manager = mesh.morphTargetManager;
  24929. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  24930. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  24931. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  24932. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  24933. }
  24934. else {
  24935. defines["MORPHTARGETS_TANGENT"] = false;
  24936. defines["MORPHTARGETS_NORMAL"] = false;
  24937. defines["MORPHTARGETS"] = false;
  24938. defines["NUM_MORPH_INFLUENCERS"] = 0;
  24939. }
  24940. }
  24941. return true;
  24942. };
  24943. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  24944. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24945. if (disableLighting === void 0) { disableLighting = false; }
  24946. if (!defines._areLightsDirty) {
  24947. return defines._needNormals;
  24948. }
  24949. var lightIndex = 0;
  24950. var needNormals = false;
  24951. var needRebuild = false;
  24952. var lightmapMode = false;
  24953. var shadowEnabled = false;
  24954. var specularEnabled = false;
  24955. if (scene.lightsEnabled && !disableLighting) {
  24956. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24957. var light = _a[_i];
  24958. needNormals = true;
  24959. if (defines["LIGHT" + lightIndex] === undefined) {
  24960. needRebuild = true;
  24961. }
  24962. defines["LIGHT" + lightIndex] = true;
  24963. defines["SPOTLIGHT" + lightIndex] = false;
  24964. defines["HEMILIGHT" + lightIndex] = false;
  24965. defines["POINTLIGHT" + lightIndex] = false;
  24966. defines["DIRLIGHT" + lightIndex] = false;
  24967. var type;
  24968. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  24969. type = "SPOTLIGHT" + lightIndex;
  24970. }
  24971. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  24972. type = "HEMILIGHT" + lightIndex;
  24973. }
  24974. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  24975. type = "POINTLIGHT" + lightIndex;
  24976. }
  24977. else {
  24978. type = "DIRLIGHT" + lightIndex;
  24979. }
  24980. defines[type] = true;
  24981. // Specular
  24982. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  24983. specularEnabled = true;
  24984. }
  24985. // Shadows
  24986. defines["SHADOW" + lightIndex] = false;
  24987. defines["SHADOWPCF" + lightIndex] = false;
  24988. defines["SHADOWESM" + lightIndex] = false;
  24989. defines["SHADOWCUBE" + lightIndex] = false;
  24990. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  24991. var shadowGenerator = light.getShadowGenerator();
  24992. if (shadowGenerator) {
  24993. shadowEnabled = true;
  24994. shadowGenerator.prepareDefines(defines, lightIndex);
  24995. }
  24996. }
  24997. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24998. lightmapMode = true;
  24999. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25000. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  25001. }
  25002. else {
  25003. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  25004. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  25005. }
  25006. lightIndex++;
  25007. if (lightIndex === maxSimultaneousLights)
  25008. break;
  25009. }
  25010. }
  25011. defines["SPECULARTERM"] = specularEnabled;
  25012. defines["SHADOWS"] = shadowEnabled;
  25013. // Resetting all other lights if any
  25014. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  25015. if (defines["LIGHT" + index] !== undefined) {
  25016. defines["LIGHT" + index] = false;
  25017. defines["HEMILIGHT" + lightIndex] = false;
  25018. defines["POINTLIGHT" + lightIndex] = false;
  25019. defines["DIRLIGHT" + lightIndex] = false;
  25020. defines["SPOTLIGHT" + lightIndex] = false;
  25021. defines["SHADOW" + lightIndex] = false;
  25022. }
  25023. }
  25024. var caps = scene.getEngine().getCaps();
  25025. if (defines["SHADOWFLOAT"] === undefined) {
  25026. needRebuild = true;
  25027. }
  25028. defines["SHADOWFLOAT"] = shadowEnabled &&
  25029. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  25030. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  25031. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  25032. if (needRebuild) {
  25033. defines.rebuild();
  25034. }
  25035. return needNormals;
  25036. };
  25037. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  25038. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25039. var uniformsList, uniformBuffersList, samplersList, defines;
  25040. if (uniformsListOrOptions.uniformsNames) {
  25041. var options = uniformsListOrOptions;
  25042. uniformsList = options.uniformsNames;
  25043. uniformBuffersList = options.uniformBuffersNames;
  25044. samplersList = options.samplers;
  25045. defines = options.defines;
  25046. maxSimultaneousLights = options.maxSimultaneousLights;
  25047. }
  25048. else {
  25049. uniformsList = uniformsListOrOptions;
  25050. }
  25051. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25052. if (!defines["LIGHT" + lightIndex]) {
  25053. break;
  25054. }
  25055. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  25056. if (uniformBuffersList) {
  25057. uniformBuffersList.push("Light" + lightIndex);
  25058. }
  25059. samplersList.push("shadowSampler" + lightIndex);
  25060. }
  25061. if (defines["NUM_MORPH_INFLUENCERS"]) {
  25062. uniformsList.push("morphTargetInfluences");
  25063. }
  25064. };
  25065. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25066. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25067. if (!defines["SHADOWS"]) {
  25068. return;
  25069. }
  25070. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25071. if (!defines["LIGHT" + lightIndex]) {
  25072. break;
  25073. }
  25074. if (lightIndex > 0) {
  25075. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25076. }
  25077. if (defines["SHADOW" + lightIndex]) {
  25078. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25079. }
  25080. if (defines["SHADOWPCF" + lightIndex]) {
  25081. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25082. }
  25083. if (defines["SHADOWESM" + lightIndex]) {
  25084. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  25085. }
  25086. }
  25087. };
  25088. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  25089. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  25090. if (influencers > 0) {
  25091. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  25092. var manager = mesh.morphTargetManager;
  25093. var normal = manager.supportsNormals && defines["NORMAL"];
  25094. var tangent = manager.supportsTangents && defines["TANGENT"];
  25095. for (var index = 0; index < influencers; index++) {
  25096. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  25097. if (normal) {
  25098. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  25099. }
  25100. if (tangent) {
  25101. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  25102. }
  25103. if (attribs.length > maxAttributesCount) {
  25104. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  25105. }
  25106. }
  25107. }
  25108. };
  25109. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25110. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25111. fallbacks.addCPUSkinningFallback(0, mesh);
  25112. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25113. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25114. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25115. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25116. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25117. }
  25118. }
  25119. };
  25120. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25121. if (defines["INSTANCES"]) {
  25122. attribs.push("world0");
  25123. attribs.push("world1");
  25124. attribs.push("world2");
  25125. attribs.push("world3");
  25126. }
  25127. };
  25128. // Bindings
  25129. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  25130. if (light.shadowEnabled && mesh.receiveShadows) {
  25131. var shadowGenerator = light.getShadowGenerator();
  25132. if (shadowGenerator) {
  25133. shadowGenerator.bindShadowLight(lightIndex, effect);
  25134. }
  25135. }
  25136. };
  25137. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25138. light.transferToEffect(effect, lightIndex + "");
  25139. };
  25140. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  25141. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25142. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  25143. var lightIndex = 0;
  25144. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25145. var light = _a[_i];
  25146. var scaledIntensity = light.getScaledIntensity();
  25147. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  25148. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25149. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  25150. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  25151. if (defines["SPECULARTERM"]) {
  25152. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  25153. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  25154. }
  25155. // Shadows
  25156. if (scene.shadowsEnabled) {
  25157. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  25158. }
  25159. light._uniformBuffer.update();
  25160. lightIndex++;
  25161. if (lightIndex === maxSimultaneousLights)
  25162. break;
  25163. }
  25164. };
  25165. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25166. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25167. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25168. effect.setColor3("vFogColor", scene.fogColor);
  25169. }
  25170. };
  25171. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25172. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25173. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25174. if (matrices) {
  25175. effect.setMatrices("mBones", matrices);
  25176. }
  25177. }
  25178. };
  25179. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25180. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25181. return;
  25182. }
  25183. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25184. };
  25185. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25186. if (defines["LOGARITHMICDEPTH"]) {
  25187. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25188. }
  25189. };
  25190. MaterialHelper.BindClipPlane = function (effect, scene) {
  25191. if (scene.clipPlane) {
  25192. var clipPlane = scene.clipPlane;
  25193. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25194. }
  25195. };
  25196. return MaterialHelper;
  25197. }());
  25198. BABYLON.MaterialHelper = MaterialHelper;
  25199. })(BABYLON || (BABYLON = {}));
  25200. //# sourceMappingURL=babylon.materialHelper.js.map
  25201. var BABYLON;
  25202. (function (BABYLON) {
  25203. var MaterialDefines = (function () {
  25204. function MaterialDefines() {
  25205. this._isDirty = true;
  25206. this._areLightsDirty = true;
  25207. this._areAttributesDirty = true;
  25208. this._areTexturesDirty = true;
  25209. this._areFresnelDirty = true;
  25210. this._areMiscDirty = true;
  25211. this._areImageProcessingDirty = true;
  25212. this._normals = false;
  25213. this._uvs = false;
  25214. this._needNormals = false;
  25215. this._needUVs = false;
  25216. }
  25217. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25218. get: function () {
  25219. return this._isDirty;
  25220. },
  25221. enumerable: true,
  25222. configurable: true
  25223. });
  25224. MaterialDefines.prototype.markAsProcessed = function () {
  25225. this._isDirty = false;
  25226. this._areAttributesDirty = false;
  25227. this._areTexturesDirty = false;
  25228. this._areFresnelDirty = false;
  25229. this._areLightsDirty = false;
  25230. this._areMiscDirty = false;
  25231. this._areImageProcessingDirty = false;
  25232. };
  25233. MaterialDefines.prototype.markAsUnprocessed = function () {
  25234. this._isDirty = true;
  25235. };
  25236. MaterialDefines.prototype.markAllAsDirty = function () {
  25237. this._areTexturesDirty = true;
  25238. this._areAttributesDirty = true;
  25239. this._areLightsDirty = true;
  25240. this._areFresnelDirty = true;
  25241. this._areMiscDirty = true;
  25242. this._areImageProcessingDirty = true;
  25243. this._isDirty = true;
  25244. };
  25245. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25246. this._areImageProcessingDirty = true;
  25247. this._isDirty = true;
  25248. };
  25249. MaterialDefines.prototype.markAsLightDirty = function () {
  25250. this._areLightsDirty = true;
  25251. this._isDirty = true;
  25252. };
  25253. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25254. this._areAttributesDirty = true;
  25255. this._isDirty = true;
  25256. };
  25257. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25258. this._areTexturesDirty = true;
  25259. this._isDirty = true;
  25260. };
  25261. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25262. this._areFresnelDirty = true;
  25263. this._isDirty = true;
  25264. };
  25265. MaterialDefines.prototype.markAsMiscDirty = function () {
  25266. this._areMiscDirty = true;
  25267. this._isDirty = true;
  25268. };
  25269. MaterialDefines.prototype.rebuild = function () {
  25270. if (this._keys) {
  25271. delete this._keys;
  25272. }
  25273. this._keys = [];
  25274. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25275. var key = _a[_i];
  25276. if (key[0] === "_") {
  25277. continue;
  25278. }
  25279. this._keys.push(key);
  25280. }
  25281. };
  25282. MaterialDefines.prototype.isEqual = function (other) {
  25283. if (this._keys.length !== other._keys.length) {
  25284. return false;
  25285. }
  25286. for (var index = 0; index < this._keys.length; index++) {
  25287. var prop = this._keys[index];
  25288. if (this[prop] !== other[prop]) {
  25289. return false;
  25290. }
  25291. }
  25292. return true;
  25293. };
  25294. MaterialDefines.prototype.cloneTo = function (other) {
  25295. if (this._keys.length !== other._keys.length) {
  25296. other._keys = this._keys.slice(0);
  25297. }
  25298. for (var index = 0; index < this._keys.length; index++) {
  25299. var prop = this._keys[index];
  25300. other[prop] = this[prop];
  25301. }
  25302. };
  25303. MaterialDefines.prototype.reset = function () {
  25304. for (var index = 0; index < this._keys.length; index++) {
  25305. var prop = this._keys[index];
  25306. if (typeof (this[prop]) === "number") {
  25307. this[prop] = 0;
  25308. }
  25309. else {
  25310. this[prop] = false;
  25311. }
  25312. }
  25313. };
  25314. MaterialDefines.prototype.toString = function () {
  25315. var result = "";
  25316. for (var index = 0; index < this._keys.length; index++) {
  25317. var prop = this._keys[index];
  25318. var value = this[prop];
  25319. if (typeof (value) === "number") {
  25320. result += "#define " + prop + " " + this[prop] + "\n";
  25321. }
  25322. else if (value) {
  25323. result += "#define " + prop + "\n";
  25324. }
  25325. }
  25326. return result;
  25327. };
  25328. return MaterialDefines;
  25329. }());
  25330. BABYLON.MaterialDefines = MaterialDefines;
  25331. var Material = (function () {
  25332. function Material(name, scene, doNotAdd) {
  25333. this.checkReadyOnEveryCall = false;
  25334. this.checkReadyOnlyOnce = false;
  25335. this.state = "";
  25336. this.alpha = 1.0;
  25337. this._backFaceCulling = true;
  25338. this.doNotSerialize = false;
  25339. this.storeEffectOnSubMeshes = false;
  25340. /**
  25341. * An event triggered when the material is disposed.
  25342. * @type {BABYLON.Observable}
  25343. */
  25344. this.onDisposeObservable = new BABYLON.Observable();
  25345. /**
  25346. * An event triggered when the material is bound.
  25347. * @type {BABYLON.Observable}
  25348. */
  25349. this.onBindObservable = new BABYLON.Observable();
  25350. /**
  25351. * An event triggered when the material is unbound.
  25352. * @type {BABYLON.Observable}
  25353. */
  25354. this.onUnBindObservable = new BABYLON.Observable();
  25355. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25356. this.disableDepthWrite = false;
  25357. this._fogEnabled = true;
  25358. this.pointSize = 1.0;
  25359. this.zOffset = 0;
  25360. this._wasPreviouslyReady = false;
  25361. this._fillMode = Material.TriangleFillMode;
  25362. this.name = name;
  25363. this.id = name || BABYLON.Tools.RandomId();
  25364. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25365. if (this._scene.useRightHandedSystem) {
  25366. this.sideOrientation = Material.ClockWiseSideOrientation;
  25367. }
  25368. else {
  25369. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25370. }
  25371. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25372. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  25373. if (!doNotAdd) {
  25374. this._scene.materials.push(this);
  25375. }
  25376. }
  25377. Object.defineProperty(Material, "TriangleFillMode", {
  25378. get: function () {
  25379. return Material._TriangleFillMode;
  25380. },
  25381. enumerable: true,
  25382. configurable: true
  25383. });
  25384. Object.defineProperty(Material, "WireFrameFillMode", {
  25385. get: function () {
  25386. return Material._WireFrameFillMode;
  25387. },
  25388. enumerable: true,
  25389. configurable: true
  25390. });
  25391. Object.defineProperty(Material, "PointFillMode", {
  25392. get: function () {
  25393. return Material._PointFillMode;
  25394. },
  25395. enumerable: true,
  25396. configurable: true
  25397. });
  25398. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25399. get: function () {
  25400. return Material._ClockWiseSideOrientation;
  25401. },
  25402. enumerable: true,
  25403. configurable: true
  25404. });
  25405. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25406. get: function () {
  25407. return Material._CounterClockWiseSideOrientation;
  25408. },
  25409. enumerable: true,
  25410. configurable: true
  25411. });
  25412. Object.defineProperty(Material, "TextureDirtyFlag", {
  25413. get: function () {
  25414. return Material._TextureDirtyFlag;
  25415. },
  25416. enumerable: true,
  25417. configurable: true
  25418. });
  25419. Object.defineProperty(Material, "LightDirtyFlag", {
  25420. get: function () {
  25421. return Material._LightDirtyFlag;
  25422. },
  25423. enumerable: true,
  25424. configurable: true
  25425. });
  25426. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25427. get: function () {
  25428. return Material._FresnelDirtyFlag;
  25429. },
  25430. enumerable: true,
  25431. configurable: true
  25432. });
  25433. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25434. get: function () {
  25435. return Material._AttributesDirtyFlag;
  25436. },
  25437. enumerable: true,
  25438. configurable: true
  25439. });
  25440. Object.defineProperty(Material, "MiscDirtyFlag", {
  25441. get: function () {
  25442. return Material._MiscDirtyFlag;
  25443. },
  25444. enumerable: true,
  25445. configurable: true
  25446. });
  25447. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25448. get: function () {
  25449. return this._backFaceCulling;
  25450. },
  25451. set: function (value) {
  25452. if (this._backFaceCulling === value) {
  25453. return;
  25454. }
  25455. this._backFaceCulling = value;
  25456. this.markAsDirty(Material.TextureDirtyFlag);
  25457. },
  25458. enumerable: true,
  25459. configurable: true
  25460. });
  25461. Object.defineProperty(Material.prototype, "onDispose", {
  25462. set: function (callback) {
  25463. if (this._onDisposeObserver) {
  25464. this.onDisposeObservable.remove(this._onDisposeObserver);
  25465. }
  25466. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25467. },
  25468. enumerable: true,
  25469. configurable: true
  25470. });
  25471. Object.defineProperty(Material.prototype, "onBind", {
  25472. set: function (callback) {
  25473. if (this._onBindObserver) {
  25474. this.onBindObservable.remove(this._onBindObserver);
  25475. }
  25476. this._onBindObserver = this.onBindObservable.add(callback);
  25477. },
  25478. enumerable: true,
  25479. configurable: true
  25480. });
  25481. Object.defineProperty(Material.prototype, "fogEnabled", {
  25482. get: function () {
  25483. return this._fogEnabled;
  25484. },
  25485. set: function (value) {
  25486. if (this._fogEnabled === value) {
  25487. return;
  25488. }
  25489. this._fogEnabled = value;
  25490. this.markAsDirty(Material.MiscDirtyFlag);
  25491. },
  25492. enumerable: true,
  25493. configurable: true
  25494. });
  25495. Object.defineProperty(Material.prototype, "wireframe", {
  25496. get: function () {
  25497. return this._fillMode === Material.WireFrameFillMode;
  25498. },
  25499. set: function (value) {
  25500. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25501. },
  25502. enumerable: true,
  25503. configurable: true
  25504. });
  25505. Object.defineProperty(Material.prototype, "pointsCloud", {
  25506. get: function () {
  25507. return this._fillMode === Material.PointFillMode;
  25508. },
  25509. set: function (value) {
  25510. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25511. },
  25512. enumerable: true,
  25513. configurable: true
  25514. });
  25515. Object.defineProperty(Material.prototype, "fillMode", {
  25516. get: function () {
  25517. return this._fillMode;
  25518. },
  25519. set: function (value) {
  25520. if (this._fillMode === value) {
  25521. return;
  25522. }
  25523. this._fillMode = value;
  25524. this.markAsDirty(Material.MiscDirtyFlag);
  25525. },
  25526. enumerable: true,
  25527. configurable: true
  25528. });
  25529. /**
  25530. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25531. * subclasses should override adding information pertainent to themselves
  25532. */
  25533. Material.prototype.toString = function (fullDetails) {
  25534. var ret = "Name: " + this.name;
  25535. if (fullDetails) {
  25536. }
  25537. return ret;
  25538. };
  25539. /**
  25540. * Child classes can use it to update shaders
  25541. */
  25542. Material.prototype.getClassName = function () {
  25543. return "Material";
  25544. };
  25545. Object.defineProperty(Material.prototype, "isFrozen", {
  25546. get: function () {
  25547. return this.checkReadyOnlyOnce;
  25548. },
  25549. enumerable: true,
  25550. configurable: true
  25551. });
  25552. Material.prototype.freeze = function () {
  25553. this.checkReadyOnlyOnce = true;
  25554. };
  25555. Material.prototype.unfreeze = function () {
  25556. this.checkReadyOnlyOnce = false;
  25557. };
  25558. Material.prototype.isReady = function (mesh, useInstances) {
  25559. return true;
  25560. };
  25561. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25562. return false;
  25563. };
  25564. Material.prototype.getEffect = function () {
  25565. return this._effect;
  25566. };
  25567. Material.prototype.getScene = function () {
  25568. return this._scene;
  25569. };
  25570. Material.prototype.needAlphaBlending = function () {
  25571. return (this.alpha < 1.0);
  25572. };
  25573. Material.prototype.needAlphaTesting = function () {
  25574. return false;
  25575. };
  25576. Material.prototype.getAlphaTestTexture = function () {
  25577. return null;
  25578. };
  25579. Material.prototype.markDirty = function () {
  25580. this._wasPreviouslyReady = false;
  25581. };
  25582. Material.prototype._preBind = function (effect) {
  25583. var engine = this._scene.getEngine();
  25584. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25585. engine.enableEffect(effect ? effect : this._effect);
  25586. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25587. };
  25588. Material.prototype.bind = function (world, mesh) {
  25589. };
  25590. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25591. };
  25592. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25593. };
  25594. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25595. sceneUbo.bindToEffect(effect, "Scene");
  25596. };
  25597. Material.prototype.bindView = function (effect) {
  25598. if (!this._useUBO) {
  25599. effect.setMatrix("view", this.getScene().getViewMatrix());
  25600. }
  25601. else {
  25602. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25603. }
  25604. };
  25605. Material.prototype.bindViewProjection = function (effect) {
  25606. if (!this._useUBO) {
  25607. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25608. }
  25609. else {
  25610. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25611. }
  25612. };
  25613. Material.prototype._afterBind = function (mesh) {
  25614. this._scene._cachedMaterial = this;
  25615. if (mesh) {
  25616. this._scene._cachedVisibility = mesh.visibility;
  25617. }
  25618. else {
  25619. this._scene._cachedVisibility = 1;
  25620. }
  25621. this.onBindObservable.notifyObservers(mesh);
  25622. if (this.disableDepthWrite) {
  25623. var engine = this._scene.getEngine();
  25624. this._cachedDepthWriteState = engine.getDepthWrite();
  25625. engine.setDepthWrite(false);
  25626. }
  25627. };
  25628. Material.prototype.unbind = function () {
  25629. this.onUnBindObservable.notifyObservers(this);
  25630. if (this.disableDepthWrite) {
  25631. var engine = this._scene.getEngine();
  25632. engine.setDepthWrite(this._cachedDepthWriteState);
  25633. }
  25634. };
  25635. Material.prototype.getActiveTextures = function () {
  25636. return [];
  25637. };
  25638. Material.prototype.hasTexture = function (texture) {
  25639. return false;
  25640. };
  25641. Material.prototype.clone = function (name) {
  25642. return null;
  25643. };
  25644. Material.prototype.getBindedMeshes = function () {
  25645. var result = new Array();
  25646. for (var index = 0; index < this._scene.meshes.length; index++) {
  25647. var mesh = this._scene.meshes[index];
  25648. if (mesh.material === this) {
  25649. result.push(mesh);
  25650. }
  25651. }
  25652. return result;
  25653. };
  25654. /**
  25655. * Force shader compilation including textures ready check
  25656. */
  25657. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25658. var _this = this;
  25659. var subMesh = new BABYLON.BaseSubMesh();
  25660. var scene = this.getScene();
  25661. var engine = scene.getEngine();
  25662. var checkReady = function () {
  25663. if (!_this._scene || !_this._scene.getEngine()) {
  25664. return;
  25665. }
  25666. if (subMesh._materialDefines) {
  25667. subMesh._materialDefines._renderId = -1;
  25668. }
  25669. var alphaTestState = engine.getAlphaTesting();
  25670. var clipPlaneState = scene.clipPlane;
  25671. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25672. if (options && options.clipPlane) {
  25673. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25674. }
  25675. if (_this.storeEffectOnSubMeshes) {
  25676. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25677. if (onCompiled) {
  25678. onCompiled(_this);
  25679. }
  25680. }
  25681. else {
  25682. setTimeout(checkReady, 16);
  25683. }
  25684. }
  25685. else {
  25686. if (_this.isReady(mesh)) {
  25687. if (onCompiled) {
  25688. onCompiled(_this);
  25689. }
  25690. }
  25691. else {
  25692. setTimeout(checkReady, 16);
  25693. }
  25694. }
  25695. engine.setAlphaTesting(alphaTestState);
  25696. if (options && options.clipPlane) {
  25697. scene.clipPlane = clipPlaneState;
  25698. }
  25699. };
  25700. checkReady();
  25701. };
  25702. Material.prototype.markAsDirty = function (flag) {
  25703. if (flag & Material.TextureDirtyFlag) {
  25704. this._markAllSubMeshesAsTexturesDirty();
  25705. }
  25706. if (flag & Material.LightDirtyFlag) {
  25707. this._markAllSubMeshesAsLightsDirty();
  25708. }
  25709. if (flag & Material.FresnelDirtyFlag) {
  25710. this._markAllSubMeshesAsFresnelDirty();
  25711. }
  25712. if (flag & Material.AttributesDirtyFlag) {
  25713. this._markAllSubMeshesAsAttributesDirty();
  25714. }
  25715. if (flag & Material.MiscDirtyFlag) {
  25716. this._markAllSubMeshesAsMiscDirty();
  25717. }
  25718. this.getScene().resetCachedMaterial();
  25719. };
  25720. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25721. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25722. var mesh = _a[_i];
  25723. if (!mesh.subMeshes) {
  25724. continue;
  25725. }
  25726. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25727. var subMesh = _c[_b];
  25728. if (subMesh.getMaterial() !== this) {
  25729. continue;
  25730. }
  25731. if (!subMesh._materialDefines) {
  25732. continue;
  25733. }
  25734. func(subMesh._materialDefines);
  25735. }
  25736. }
  25737. };
  25738. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25739. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25740. };
  25741. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25742. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25743. };
  25744. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25745. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25746. };
  25747. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25748. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25749. };
  25750. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  25751. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  25752. };
  25753. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  25754. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  25755. };
  25756. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25757. // Animations
  25758. this.getScene().stopAnimation(this);
  25759. // Remove from scene
  25760. var index = this._scene.materials.indexOf(this);
  25761. if (index >= 0) {
  25762. this._scene.materials.splice(index, 1);
  25763. }
  25764. // Remove from meshes
  25765. for (index = 0; index < this._scene.meshes.length; index++) {
  25766. var mesh = this._scene.meshes[index];
  25767. if (mesh.material === this) {
  25768. mesh.material = null;
  25769. if (mesh.geometry) {
  25770. var geometry = mesh.geometry;
  25771. if (this.storeEffectOnSubMeshes) {
  25772. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  25773. var subMesh = _a[_i];
  25774. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  25775. }
  25776. }
  25777. else {
  25778. geometry._releaseVertexArrayObject(this._effect);
  25779. }
  25780. }
  25781. }
  25782. }
  25783. this._uniformBuffer.dispose();
  25784. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25785. if (forceDisposeEffect && this._effect) {
  25786. if (this.storeEffectOnSubMeshes) {
  25787. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25788. var subMesh = _c[_b];
  25789. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  25790. }
  25791. }
  25792. else {
  25793. this._scene.getEngine()._releaseEffect(this._effect);
  25794. }
  25795. this._effect = null;
  25796. }
  25797. // Callback
  25798. this.onDisposeObservable.notifyObservers(this);
  25799. this.onDisposeObservable.clear();
  25800. this.onBindObservable.clear();
  25801. this.onUnBindObservable.clear();
  25802. };
  25803. Material.prototype.serialize = function () {
  25804. return BABYLON.SerializationHelper.Serialize(this);
  25805. };
  25806. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25807. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25808. multiMaterial.id = parsedMultiMaterial.id;
  25809. if (BABYLON.Tags) {
  25810. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25811. }
  25812. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25813. var subMatId = parsedMultiMaterial.materials[matIndex];
  25814. if (subMatId) {
  25815. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25816. }
  25817. else {
  25818. multiMaterial.subMaterials.push(null);
  25819. }
  25820. }
  25821. return multiMaterial;
  25822. };
  25823. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25824. if (!parsedMaterial.customType) {
  25825. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25826. }
  25827. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  25828. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  25829. if (!BABYLON.LegacyPBRMaterial) {
  25830. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  25831. return;
  25832. }
  25833. }
  25834. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25835. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25836. ;
  25837. };
  25838. Material._TriangleFillMode = 0;
  25839. Material._WireFrameFillMode = 1;
  25840. Material._PointFillMode = 2;
  25841. Material._ClockWiseSideOrientation = 0;
  25842. Material._CounterClockWiseSideOrientation = 1;
  25843. Material._TextureDirtyFlag = 1;
  25844. Material._LightDirtyFlag = 2;
  25845. Material._FresnelDirtyFlag = 4;
  25846. Material._AttributesDirtyFlag = 8;
  25847. Material._MiscDirtyFlag = 16;
  25848. __decorate([
  25849. BABYLON.serialize()
  25850. ], Material.prototype, "id", void 0);
  25851. __decorate([
  25852. BABYLON.serialize()
  25853. ], Material.prototype, "name", void 0);
  25854. __decorate([
  25855. BABYLON.serialize()
  25856. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25857. __decorate([
  25858. BABYLON.serialize()
  25859. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25860. __decorate([
  25861. BABYLON.serialize()
  25862. ], Material.prototype, "state", void 0);
  25863. __decorate([
  25864. BABYLON.serialize()
  25865. ], Material.prototype, "alpha", void 0);
  25866. __decorate([
  25867. BABYLON.serialize("backFaceCulling")
  25868. ], Material.prototype, "_backFaceCulling", void 0);
  25869. __decorate([
  25870. BABYLON.serialize()
  25871. ], Material.prototype, "sideOrientation", void 0);
  25872. __decorate([
  25873. BABYLON.serialize()
  25874. ], Material.prototype, "alphaMode", void 0);
  25875. __decorate([
  25876. BABYLON.serialize()
  25877. ], Material.prototype, "disableDepthWrite", void 0);
  25878. __decorate([
  25879. BABYLON.serialize("fogEnabled")
  25880. ], Material.prototype, "_fogEnabled", void 0);
  25881. __decorate([
  25882. BABYLON.serialize()
  25883. ], Material.prototype, "pointSize", void 0);
  25884. __decorate([
  25885. BABYLON.serialize()
  25886. ], Material.prototype, "zOffset", void 0);
  25887. __decorate([
  25888. BABYLON.serialize()
  25889. ], Material.prototype, "wireframe", null);
  25890. __decorate([
  25891. BABYLON.serialize()
  25892. ], Material.prototype, "pointsCloud", null);
  25893. __decorate([
  25894. BABYLON.serialize()
  25895. ], Material.prototype, "fillMode", null);
  25896. return Material;
  25897. }());
  25898. BABYLON.Material = Material;
  25899. })(BABYLON || (BABYLON = {}));
  25900. //# sourceMappingURL=babylon.material.js.map
  25901. var BABYLON;
  25902. (function (BABYLON) {
  25903. var UniformBuffer = (function () {
  25904. /**
  25905. * Uniform buffer objects.
  25906. *
  25907. * Handles blocks of uniform on the GPU.
  25908. *
  25909. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  25910. *
  25911. * For more information, please refer to :
  25912. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  25913. */
  25914. function UniformBuffer(engine, data, dynamic) {
  25915. this._engine = engine;
  25916. this._noUBO = !engine.supportsUniformBuffers;
  25917. this._dynamic = dynamic;
  25918. this._data = data || [];
  25919. this._uniformLocations = {};
  25920. this._uniformSizes = {};
  25921. this._uniformLocationPointer = 0;
  25922. this._needSync = false;
  25923. if (this._noUBO) {
  25924. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  25925. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  25926. this.updateFloat = this._updateFloatForEffect;
  25927. this.updateFloat2 = this._updateFloat2ForEffect;
  25928. this.updateFloat3 = this._updateFloat3ForEffect;
  25929. this.updateFloat4 = this._updateFloat4ForEffect;
  25930. this.updateMatrix = this._updateMatrixForEffect;
  25931. this.updateVector3 = this._updateVector3ForEffect;
  25932. this.updateVector4 = this._updateVector4ForEffect;
  25933. this.updateColor3 = this._updateColor3ForEffect;
  25934. this.updateColor4 = this._updateColor4ForEffect;
  25935. }
  25936. else {
  25937. this._engine._uniformBuffers.push(this);
  25938. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  25939. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  25940. this.updateFloat = this._updateFloatForUniform;
  25941. this.updateFloat2 = this._updateFloat2ForUniform;
  25942. this.updateFloat3 = this._updateFloat3ForUniform;
  25943. this.updateFloat4 = this._updateFloat4ForUniform;
  25944. this.updateMatrix = this._updateMatrixForUniform;
  25945. this.updateVector3 = this._updateVector3ForUniform;
  25946. this.updateVector4 = this._updateVector4ForUniform;
  25947. this.updateColor3 = this._updateColor3ForUniform;
  25948. this.updateColor4 = this._updateColor4ForUniform;
  25949. }
  25950. }
  25951. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  25952. // Properties
  25953. /**
  25954. * Indicates if the buffer is using the WebGL2 UBO implementation,
  25955. * or just falling back on setUniformXXX calls.
  25956. */
  25957. get: function () {
  25958. return !this._noUBO;
  25959. },
  25960. enumerable: true,
  25961. configurable: true
  25962. });
  25963. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  25964. /**
  25965. * Indicates if the WebGL underlying uniform buffer is in sync
  25966. * with the javascript cache data.
  25967. */
  25968. get: function () {
  25969. return !this._needSync;
  25970. },
  25971. enumerable: true,
  25972. configurable: true
  25973. });
  25974. /**
  25975. * Indicates if the WebGL underlying uniform buffer is dynamic.
  25976. * Also, a dynamic UniformBuffer will disable cache verification and always
  25977. * update the underlying WebGL uniform buffer to the GPU.
  25978. */
  25979. UniformBuffer.prototype.isDynamic = function () {
  25980. return this._dynamic;
  25981. };
  25982. /**
  25983. * The data cache on JS side.
  25984. */
  25985. UniformBuffer.prototype.getData = function () {
  25986. return this._bufferData;
  25987. };
  25988. /**
  25989. * The underlying WebGL Uniform buffer.
  25990. */
  25991. UniformBuffer.prototype.getBuffer = function () {
  25992. return this._buffer;
  25993. };
  25994. /**
  25995. * std140 layout specifies how to align data within an UBO structure.
  25996. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  25997. * for specs.
  25998. */
  25999. UniformBuffer.prototype._fillAlignment = function (size) {
  26000. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  26001. // and 4x4 matrices
  26002. // TODO : change if other types are used
  26003. var alignment;
  26004. if (size <= 2) {
  26005. alignment = size;
  26006. }
  26007. else {
  26008. alignment = 4;
  26009. }
  26010. if ((this._uniformLocationPointer % alignment) !== 0) {
  26011. var oldPointer = this._uniformLocationPointer;
  26012. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  26013. var diff = this._uniformLocationPointer - oldPointer;
  26014. for (var i = 0; i < diff; i++) {
  26015. this._data.push(0);
  26016. }
  26017. }
  26018. };
  26019. /**
  26020. * Adds an uniform in the buffer.
  26021. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  26022. * for the layout to be correct !
  26023. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26024. * @param {number|number[]} size Data size, or data directly.
  26025. */
  26026. UniformBuffer.prototype.addUniform = function (name, size) {
  26027. if (this._noUBO) {
  26028. return;
  26029. }
  26030. if (this._uniformLocations[name] !== undefined) {
  26031. // Already existing uniform
  26032. return;
  26033. }
  26034. // This function must be called in the order of the shader layout !
  26035. // size can be the size of the uniform, or data directly
  26036. var data;
  26037. if (size instanceof Array) {
  26038. data = size;
  26039. size = data.length;
  26040. }
  26041. else {
  26042. size = size;
  26043. data = [];
  26044. // Fill with zeros
  26045. for (var i = 0; i < size; i++) {
  26046. data.push(0);
  26047. }
  26048. }
  26049. this._fillAlignment(size);
  26050. this._uniformSizes[name] = size;
  26051. this._uniformLocations[name] = this._uniformLocationPointer;
  26052. this._uniformLocationPointer += size;
  26053. for (var i = 0; i < size; i++) {
  26054. this._data.push(data[i]);
  26055. }
  26056. this._needSync = true;
  26057. };
  26058. /**
  26059. * Wrapper for addUniform.
  26060. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26061. * @param {Matrix} mat A 4x4 matrix.
  26062. */
  26063. UniformBuffer.prototype.addMatrix = function (name, mat) {
  26064. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  26065. };
  26066. /**
  26067. * Wrapper for addUniform.
  26068. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26069. * @param {number} x
  26070. * @param {number} y
  26071. */
  26072. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  26073. var temp = [x, y];
  26074. this.addUniform(name, temp);
  26075. };
  26076. /**
  26077. * Wrapper for addUniform.
  26078. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26079. * @param {number} x
  26080. * @param {number} y
  26081. * @param {number} z
  26082. */
  26083. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  26084. var temp = [x, y, z];
  26085. this.addUniform(name, temp);
  26086. };
  26087. /**
  26088. * Wrapper for addUniform.
  26089. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26090. * @param {Color3} color
  26091. */
  26092. UniformBuffer.prototype.addColor3 = function (name, color) {
  26093. var temp = [];
  26094. color.toArray(temp);
  26095. this.addUniform(name, temp);
  26096. };
  26097. /**
  26098. * Wrapper for addUniform.
  26099. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26100. * @param {Color3} color
  26101. * @param {number} alpha
  26102. */
  26103. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  26104. var temp = [];
  26105. color.toArray(temp);
  26106. temp.push(alpha);
  26107. this.addUniform(name, temp);
  26108. };
  26109. /**
  26110. * Wrapper for addUniform.
  26111. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26112. * @param {Vector3} vector
  26113. */
  26114. UniformBuffer.prototype.addVector3 = function (name, vector) {
  26115. var temp = [];
  26116. vector.toArray(temp);
  26117. this.addUniform(name, temp);
  26118. };
  26119. /**
  26120. * Wrapper for addUniform.
  26121. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26122. */
  26123. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  26124. this.addUniform(name, 12);
  26125. };
  26126. /**
  26127. * Wrapper for addUniform.
  26128. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26129. */
  26130. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  26131. this.addUniform(name, 8);
  26132. };
  26133. /**
  26134. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  26135. */
  26136. UniformBuffer.prototype.create = function () {
  26137. if (this._noUBO) {
  26138. return;
  26139. }
  26140. if (this._buffer) {
  26141. return; // nothing to do
  26142. }
  26143. // See spec, alignment must be filled as a vec4
  26144. this._fillAlignment(4);
  26145. this._bufferData = new Float32Array(this._data);
  26146. this._rebuild();
  26147. this._needSync = true;
  26148. };
  26149. UniformBuffer.prototype._rebuild = function () {
  26150. if (this._noUBO) {
  26151. return;
  26152. }
  26153. if (this._dynamic) {
  26154. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  26155. }
  26156. else {
  26157. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  26158. }
  26159. };
  26160. /**
  26161. * Updates the WebGL Uniform Buffer on the GPU.
  26162. * If the `dynamic` flag is set to true, no cache comparison is done.
  26163. * Otherwise, the buffer will be updated only if the cache differs.
  26164. */
  26165. UniformBuffer.prototype.update = function () {
  26166. if (!this._buffer) {
  26167. this.create();
  26168. return;
  26169. }
  26170. if (!this._dynamic && !this._needSync) {
  26171. return;
  26172. }
  26173. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  26174. this._needSync = false;
  26175. };
  26176. /**
  26177. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26178. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26179. * @param {number[]|Float32Array} data Flattened data
  26180. * @param {number} size Size of the data.
  26181. */
  26182. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26183. var location = this._uniformLocations[uniformName];
  26184. if (location === undefined) {
  26185. if (this._buffer) {
  26186. // Cannot add an uniform if the buffer is already created
  26187. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26188. return;
  26189. }
  26190. this.addUniform(uniformName, size);
  26191. location = this._uniformLocations[uniformName];
  26192. }
  26193. if (!this._buffer) {
  26194. this.create();
  26195. }
  26196. if (!this._dynamic) {
  26197. // Cache for static uniform buffers
  26198. var changed = false;
  26199. for (var i = 0; i < size; i++) {
  26200. if (this._bufferData[location + i] !== data[i]) {
  26201. changed = true;
  26202. this._bufferData[location + i] = data[i];
  26203. }
  26204. }
  26205. this._needSync = this._needSync || changed;
  26206. }
  26207. else {
  26208. // No cache for dynamic
  26209. for (var i = 0; i < size; i++) {
  26210. this._bufferData[location + i] = data[i];
  26211. }
  26212. }
  26213. };
  26214. // Update methods
  26215. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26216. // To match std140, matrix must be realigned
  26217. for (var i = 0; i < 3; i++) {
  26218. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26219. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26220. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26221. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26222. }
  26223. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26224. };
  26225. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26226. this._currentEffect.setMatrix3x3(name, matrix);
  26227. };
  26228. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26229. this._currentEffect.setMatrix2x2(name, matrix);
  26230. };
  26231. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26232. // To match std140, matrix must be realigned
  26233. for (var i = 0; i < 2; i++) {
  26234. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26235. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26236. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26237. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26238. }
  26239. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26240. };
  26241. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26242. this._currentEffect.setFloat(name, x);
  26243. };
  26244. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26245. UniformBuffer._tempBuffer[0] = x;
  26246. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26247. };
  26248. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26249. if (suffix === void 0) { suffix = ""; }
  26250. this._currentEffect.setFloat2(name + suffix, x, y);
  26251. };
  26252. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26253. if (suffix === void 0) { suffix = ""; }
  26254. UniformBuffer._tempBuffer[0] = x;
  26255. UniformBuffer._tempBuffer[1] = y;
  26256. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26257. };
  26258. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26259. if (suffix === void 0) { suffix = ""; }
  26260. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26261. };
  26262. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26263. if (suffix === void 0) { suffix = ""; }
  26264. UniformBuffer._tempBuffer[0] = x;
  26265. UniformBuffer._tempBuffer[1] = y;
  26266. UniformBuffer._tempBuffer[2] = z;
  26267. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26268. };
  26269. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26270. if (suffix === void 0) { suffix = ""; }
  26271. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26272. };
  26273. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26274. if (suffix === void 0) { suffix = ""; }
  26275. UniformBuffer._tempBuffer[0] = x;
  26276. UniformBuffer._tempBuffer[1] = y;
  26277. UniformBuffer._tempBuffer[2] = z;
  26278. UniformBuffer._tempBuffer[3] = w;
  26279. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26280. };
  26281. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26282. this._currentEffect.setMatrix(name, mat);
  26283. };
  26284. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26285. this.updateUniform(name, mat.toArray(), 16);
  26286. };
  26287. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26288. this._currentEffect.setVector3(name, vector);
  26289. };
  26290. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26291. vector.toArray(UniformBuffer._tempBuffer);
  26292. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26293. };
  26294. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26295. this._currentEffect.setVector4(name, vector);
  26296. };
  26297. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26298. vector.toArray(UniformBuffer._tempBuffer);
  26299. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26300. };
  26301. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26302. if (suffix === void 0) { suffix = ""; }
  26303. this._currentEffect.setColor3(name + suffix, color);
  26304. };
  26305. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26306. if (suffix === void 0) { suffix = ""; }
  26307. color.toArray(UniformBuffer._tempBuffer);
  26308. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26309. };
  26310. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26311. if (suffix === void 0) { suffix = ""; }
  26312. this._currentEffect.setColor4(name + suffix, color, alpha);
  26313. };
  26314. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26315. if (suffix === void 0) { suffix = ""; }
  26316. color.toArray(UniformBuffer._tempBuffer);
  26317. UniformBuffer._tempBuffer[3] = alpha;
  26318. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26319. };
  26320. /**
  26321. * Sets a sampler uniform on the effect.
  26322. * @param {string} name Name of the sampler.
  26323. * @param {Texture} texture
  26324. */
  26325. UniformBuffer.prototype.setTexture = function (name, texture) {
  26326. this._currentEffect.setTexture(name, texture);
  26327. };
  26328. /**
  26329. * Directly updates the value of the uniform in the cache AND on the GPU.
  26330. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26331. * @param {number[]|Float32Array} data Flattened data
  26332. */
  26333. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26334. this.updateUniform(uniformName, data, data.length);
  26335. this.update();
  26336. };
  26337. /**
  26338. * Binds this uniform buffer to an effect.
  26339. * @param {Effect} effect
  26340. * @param {string} name Name of the uniform block in the shader.
  26341. */
  26342. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26343. this._currentEffect = effect;
  26344. if (this._noUBO) {
  26345. return;
  26346. }
  26347. effect.bindUniformBuffer(this._buffer, name);
  26348. };
  26349. /**
  26350. * Disposes the uniform buffer.
  26351. */
  26352. UniformBuffer.prototype.dispose = function () {
  26353. if (this._noUBO) {
  26354. return;
  26355. }
  26356. var index = this._engine._uniformBuffers.indexOf(this);
  26357. if (index !== -1) {
  26358. this._engine._uniformBuffers.splice(index, 1);
  26359. }
  26360. if (!this._buffer) {
  26361. return;
  26362. }
  26363. if (this._engine._releaseBuffer(this._buffer)) {
  26364. this._buffer = null;
  26365. }
  26366. };
  26367. // Pool for avoiding memory leaks
  26368. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26369. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26370. return UniformBuffer;
  26371. }());
  26372. BABYLON.UniformBuffer = UniformBuffer;
  26373. })(BABYLON || (BABYLON = {}));
  26374. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26375. var BABYLON;
  26376. (function (BABYLON) {
  26377. var PushMaterial = (function (_super) {
  26378. __extends(PushMaterial, _super);
  26379. function PushMaterial(name, scene) {
  26380. var _this = _super.call(this, name, scene) || this;
  26381. _this.storeEffectOnSubMeshes = true;
  26382. return _this;
  26383. }
  26384. PushMaterial.prototype.getEffect = function () {
  26385. return this._activeEffect;
  26386. };
  26387. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26388. if (!mesh) {
  26389. return false;
  26390. }
  26391. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26392. return true;
  26393. }
  26394. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26395. };
  26396. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26397. this._activeEffect.setMatrix("world", world);
  26398. };
  26399. PushMaterial.prototype.bind = function (world, mesh) {
  26400. if (!mesh) {
  26401. return;
  26402. }
  26403. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26404. };
  26405. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26406. _super.prototype._afterBind.call(this, mesh);
  26407. this.getScene()._cachedEffect = effect;
  26408. };
  26409. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26410. if (visibility === void 0) { visibility = 1; }
  26411. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26412. };
  26413. return PushMaterial;
  26414. }(BABYLON.Material));
  26415. BABYLON.PushMaterial = PushMaterial;
  26416. })(BABYLON || (BABYLON = {}));
  26417. //# sourceMappingURL=babylon.pushMaterial.js.map
  26418. var BABYLON;
  26419. (function (BABYLON) {
  26420. var VertexData = (function () {
  26421. function VertexData() {
  26422. }
  26423. VertexData.prototype.set = function (data, kind) {
  26424. switch (kind) {
  26425. case BABYLON.VertexBuffer.PositionKind:
  26426. this.positions = data;
  26427. break;
  26428. case BABYLON.VertexBuffer.NormalKind:
  26429. this.normals = data;
  26430. break;
  26431. case BABYLON.VertexBuffer.TangentKind:
  26432. this.tangents = data;
  26433. break;
  26434. case BABYLON.VertexBuffer.UVKind:
  26435. this.uvs = data;
  26436. break;
  26437. case BABYLON.VertexBuffer.UV2Kind:
  26438. this.uvs2 = data;
  26439. break;
  26440. case BABYLON.VertexBuffer.UV3Kind:
  26441. this.uvs3 = data;
  26442. break;
  26443. case BABYLON.VertexBuffer.UV4Kind:
  26444. this.uvs4 = data;
  26445. break;
  26446. case BABYLON.VertexBuffer.UV5Kind:
  26447. this.uvs5 = data;
  26448. break;
  26449. case BABYLON.VertexBuffer.UV6Kind:
  26450. this.uvs6 = data;
  26451. break;
  26452. case BABYLON.VertexBuffer.ColorKind:
  26453. this.colors = data;
  26454. break;
  26455. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26456. this.matricesIndices = data;
  26457. break;
  26458. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26459. this.matricesWeights = data;
  26460. break;
  26461. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26462. this.matricesIndicesExtra = data;
  26463. break;
  26464. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26465. this.matricesWeightsExtra = data;
  26466. break;
  26467. }
  26468. };
  26469. /**
  26470. * Associates the vertexData to the passed Mesh.
  26471. * Sets it as updatable or not (default `false`).
  26472. * Returns the VertexData.
  26473. */
  26474. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26475. this._applyTo(mesh, updatable);
  26476. return this;
  26477. };
  26478. /**
  26479. * Associates the vertexData to the passed Geometry.
  26480. * Sets it as updatable or not (default `false`).
  26481. * Returns the VertexData.
  26482. */
  26483. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26484. this._applyTo(geometry, updatable);
  26485. return this;
  26486. };
  26487. /**
  26488. * Updates the associated mesh.
  26489. * Returns the VertexData.
  26490. */
  26491. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26492. this._update(mesh);
  26493. return this;
  26494. };
  26495. /**
  26496. * Updates the associated geometry.
  26497. * Returns the VertexData.
  26498. */
  26499. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26500. this._update(geometry);
  26501. return this;
  26502. };
  26503. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26504. if (this.positions) {
  26505. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26506. }
  26507. if (this.normals) {
  26508. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26509. }
  26510. if (this.tangents) {
  26511. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26512. }
  26513. if (this.uvs) {
  26514. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26515. }
  26516. if (this.uvs2) {
  26517. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26518. }
  26519. if (this.uvs3) {
  26520. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26521. }
  26522. if (this.uvs4) {
  26523. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26524. }
  26525. if (this.uvs5) {
  26526. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26527. }
  26528. if (this.uvs6) {
  26529. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26530. }
  26531. if (this.colors) {
  26532. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26533. }
  26534. if (this.matricesIndices) {
  26535. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26536. }
  26537. if (this.matricesWeights) {
  26538. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26539. }
  26540. if (this.matricesIndicesExtra) {
  26541. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26542. }
  26543. if (this.matricesWeightsExtra) {
  26544. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26545. }
  26546. if (this.indices) {
  26547. meshOrGeometry.setIndices(this.indices);
  26548. }
  26549. return this;
  26550. };
  26551. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26552. if (this.positions) {
  26553. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26554. }
  26555. if (this.normals) {
  26556. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26557. }
  26558. if (this.tangents) {
  26559. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26560. }
  26561. if (this.uvs) {
  26562. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26563. }
  26564. if (this.uvs2) {
  26565. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26566. }
  26567. if (this.uvs3) {
  26568. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26569. }
  26570. if (this.uvs4) {
  26571. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26572. }
  26573. if (this.uvs5) {
  26574. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26575. }
  26576. if (this.uvs6) {
  26577. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26578. }
  26579. if (this.colors) {
  26580. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26581. }
  26582. if (this.matricesIndices) {
  26583. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26584. }
  26585. if (this.matricesWeights) {
  26586. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26587. }
  26588. if (this.matricesIndicesExtra) {
  26589. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26590. }
  26591. if (this.matricesWeightsExtra) {
  26592. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26593. }
  26594. if (this.indices) {
  26595. meshOrGeometry.setIndices(this.indices);
  26596. }
  26597. return this;
  26598. };
  26599. /**
  26600. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26601. * Returns the VertexData.
  26602. */
  26603. VertexData.prototype.transform = function (matrix) {
  26604. var transformed = BABYLON.Vector3.Zero();
  26605. var index;
  26606. if (this.positions) {
  26607. var position = BABYLON.Vector3.Zero();
  26608. for (index = 0; index < this.positions.length; index += 3) {
  26609. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26610. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26611. this.positions[index] = transformed.x;
  26612. this.positions[index + 1] = transformed.y;
  26613. this.positions[index + 2] = transformed.z;
  26614. }
  26615. }
  26616. if (this.normals) {
  26617. var normal = BABYLON.Vector3.Zero();
  26618. for (index = 0; index < this.normals.length; index += 3) {
  26619. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26620. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26621. this.normals[index] = transformed.x;
  26622. this.normals[index + 1] = transformed.y;
  26623. this.normals[index + 2] = transformed.z;
  26624. }
  26625. }
  26626. if (this.tangents) {
  26627. var tangent = BABYLON.Vector4.Zero();
  26628. var tangentTransformed = BABYLON.Vector4.Zero();
  26629. for (index = 0; index < this.tangents.length; index += 4) {
  26630. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26631. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26632. this.tangents[index] = tangentTransformed.x;
  26633. this.tangents[index + 1] = tangentTransformed.y;
  26634. this.tangents[index + 2] = tangentTransformed.z;
  26635. this.tangents[index + 3] = tangentTransformed.w;
  26636. }
  26637. }
  26638. return this;
  26639. };
  26640. /**
  26641. * Merges the passed VertexData into the current one.
  26642. * Returns the modified VertexData.
  26643. */
  26644. VertexData.prototype.merge = function (other) {
  26645. if (other.indices) {
  26646. if (!this.indices) {
  26647. this.indices = [];
  26648. }
  26649. var offset = this.positions ? this.positions.length / 3 : 0;
  26650. for (var index = 0; index < other.indices.length; index++) {
  26651. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26652. this.indices.push(other.indices[index] + offset);
  26653. }
  26654. }
  26655. this.positions = this._mergeElement(this.positions, other.positions);
  26656. this.normals = this._mergeElement(this.normals, other.normals);
  26657. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26658. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26659. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26660. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26661. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26662. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26663. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26664. this.colors = this._mergeElement(this.colors, other.colors);
  26665. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26666. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26667. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26668. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26669. return this;
  26670. };
  26671. VertexData.prototype._mergeElement = function (source, other) {
  26672. if (!other)
  26673. return source;
  26674. if (!source)
  26675. return other;
  26676. var len = other.length + source.length;
  26677. var isSrcTypedArray = source instanceof Float32Array;
  26678. var isOthTypedArray = other instanceof Float32Array;
  26679. // use non-loop method when the source is Float32Array
  26680. if (isSrcTypedArray) {
  26681. var ret32 = new Float32Array(len);
  26682. ret32.set(source);
  26683. ret32.set(other, source.length);
  26684. return ret32;
  26685. // source is number[], when other is also use concat
  26686. }
  26687. else if (!isOthTypedArray) {
  26688. return source.concat(other);
  26689. // source is a number[], but other is a Float32Array, loop required
  26690. }
  26691. else {
  26692. var ret = source.slice(0); // copy source to a separate array
  26693. for (var i = 0, len = other.length; i < len; i++) {
  26694. ret.push(other[i]);
  26695. }
  26696. return ret;
  26697. }
  26698. };
  26699. /**
  26700. * Serializes the VertexData.
  26701. * Returns a serialized object.
  26702. */
  26703. VertexData.prototype.serialize = function () {
  26704. var serializationObject = this.serialize();
  26705. if (this.positions) {
  26706. serializationObject.positions = this.positions;
  26707. }
  26708. if (this.normals) {
  26709. serializationObject.normals = this.normals;
  26710. }
  26711. if (this.tangents) {
  26712. serializationObject.tangents = this.tangents;
  26713. }
  26714. if (this.uvs) {
  26715. serializationObject.uvs = this.uvs;
  26716. }
  26717. if (this.uvs2) {
  26718. serializationObject.uvs2 = this.uvs2;
  26719. }
  26720. if (this.uvs3) {
  26721. serializationObject.uvs3 = this.uvs3;
  26722. }
  26723. if (this.uvs4) {
  26724. serializationObject.uvs4 = this.uvs4;
  26725. }
  26726. if (this.uvs5) {
  26727. serializationObject.uvs5 = this.uvs5;
  26728. }
  26729. if (this.uvs6) {
  26730. serializationObject.uvs6 = this.uvs6;
  26731. }
  26732. if (this.colors) {
  26733. serializationObject.colors = this.colors;
  26734. }
  26735. if (this.matricesIndices) {
  26736. serializationObject.matricesIndices = this.matricesIndices;
  26737. serializationObject.matricesIndices._isExpanded = true;
  26738. }
  26739. if (this.matricesWeights) {
  26740. serializationObject.matricesWeights = this.matricesWeights;
  26741. }
  26742. if (this.matricesIndicesExtra) {
  26743. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26744. serializationObject.matricesIndicesExtra._isExpanded = true;
  26745. }
  26746. if (this.matricesWeightsExtra) {
  26747. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26748. }
  26749. serializationObject.indices = this.indices;
  26750. return serializationObject;
  26751. };
  26752. // Statics
  26753. /**
  26754. * Returns the object VertexData associated to the passed mesh.
  26755. */
  26756. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  26757. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  26758. };
  26759. /**
  26760. * Returns the object VertexData associated to the passed geometry.
  26761. */
  26762. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  26763. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  26764. };
  26765. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  26766. var result = new VertexData();
  26767. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26768. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  26769. }
  26770. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26771. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  26772. }
  26773. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26774. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  26775. }
  26776. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26777. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  26778. }
  26779. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26780. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  26781. }
  26782. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26783. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  26784. }
  26785. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26786. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  26787. }
  26788. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26789. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  26790. }
  26791. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26792. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  26793. }
  26794. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26795. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  26796. }
  26797. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26798. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  26799. }
  26800. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26801. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  26802. }
  26803. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26804. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  26805. }
  26806. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26807. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  26808. }
  26809. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26810. return result;
  26811. };
  26812. /**
  26813. * Creates the vertexData of the Ribbon.
  26814. */
  26815. VertexData.CreateRibbon = function (options) {
  26816. var pathArray = options.pathArray;
  26817. var closeArray = options.closeArray || false;
  26818. var closePath = options.closePath || false;
  26819. var invertUV = options.invertUV || false;
  26820. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26821. var offset = options.offset || defaultOffset;
  26822. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26823. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26824. var customUV = options.uvs;
  26825. var customColors = options.colors;
  26826. var positions = [];
  26827. var indices = [];
  26828. var normals = [];
  26829. var uvs = [];
  26830. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26831. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26832. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26833. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26834. var minlg; // minimal length among all paths from pathArray
  26835. var lg = []; // array of path lengths : nb of vertex per path
  26836. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26837. var p; // path iterator
  26838. var i; // point iterator
  26839. var j; // point iterator
  26840. // if single path in pathArray
  26841. if (pathArray.length < 2) {
  26842. var ar1 = [];
  26843. var ar2 = [];
  26844. for (i = 0; i < pathArray[0].length - offset; i++) {
  26845. ar1.push(pathArray[0][i]);
  26846. ar2.push(pathArray[0][i + offset]);
  26847. }
  26848. pathArray = [ar1, ar2];
  26849. }
  26850. // positions and horizontal distances (u)
  26851. var idc = 0;
  26852. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  26853. var path;
  26854. var l;
  26855. minlg = pathArray[0].length;
  26856. var vectlg;
  26857. var dist;
  26858. for (p = 0; p < pathArray.length; p++) {
  26859. uTotalDistance[p] = 0;
  26860. us[p] = [0];
  26861. path = pathArray[p];
  26862. l = path.length;
  26863. minlg = (minlg < l) ? minlg : l;
  26864. j = 0;
  26865. while (j < l) {
  26866. positions.push(path[j].x, path[j].y, path[j].z);
  26867. if (j > 0) {
  26868. vectlg = path[j].subtract(path[j - 1]).length();
  26869. dist = vectlg + uTotalDistance[p];
  26870. us[p].push(dist);
  26871. uTotalDistance[p] = dist;
  26872. }
  26873. j++;
  26874. }
  26875. if (closePath) {
  26876. j--;
  26877. positions.push(path[0].x, path[0].y, path[0].z);
  26878. vectlg = path[j].subtract(path[0]).length();
  26879. dist = vectlg + uTotalDistance[p];
  26880. us[p].push(dist);
  26881. uTotalDistance[p] = dist;
  26882. }
  26883. lg[p] = l + closePathCorr;
  26884. idx[p] = idc;
  26885. idc += (l + closePathCorr);
  26886. }
  26887. // vertical distances (v)
  26888. var path1;
  26889. var path2;
  26890. var vertex1;
  26891. var vertex2;
  26892. for (i = 0; i < minlg + closePathCorr; i++) {
  26893. vTotalDistance[i] = 0;
  26894. vs[i] = [0];
  26895. for (p = 0; p < pathArray.length - 1; p++) {
  26896. path1 = pathArray[p];
  26897. path2 = pathArray[p + 1];
  26898. if (i === minlg) {
  26899. vertex1 = path1[0];
  26900. vertex2 = path2[0];
  26901. }
  26902. else {
  26903. vertex1 = path1[i];
  26904. vertex2 = path2[i];
  26905. }
  26906. vectlg = vertex2.subtract(vertex1).length();
  26907. dist = vectlg + vTotalDistance[i];
  26908. vs[i].push(dist);
  26909. vTotalDistance[i] = dist;
  26910. }
  26911. if (closeArray) {
  26912. path1 = pathArray[p];
  26913. path2 = pathArray[0];
  26914. if (i === minlg) {
  26915. vertex2 = path2[0];
  26916. }
  26917. vectlg = vertex2.subtract(vertex1).length();
  26918. dist = vectlg + vTotalDistance[i];
  26919. vTotalDistance[i] = dist;
  26920. }
  26921. }
  26922. // uvs
  26923. var u;
  26924. var v;
  26925. if (customUV) {
  26926. for (p = 0; p < customUV.length; p++) {
  26927. uvs.push(customUV[p].x, customUV[p].y);
  26928. }
  26929. }
  26930. else {
  26931. for (p = 0; p < pathArray.length; p++) {
  26932. for (i = 0; i < minlg + closePathCorr; i++) {
  26933. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  26934. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  26935. if (invertUV) {
  26936. uvs.push(v, u);
  26937. }
  26938. else {
  26939. uvs.push(u, v);
  26940. }
  26941. }
  26942. }
  26943. }
  26944. // indices
  26945. p = 0; // path index
  26946. var pi = 0; // positions array index
  26947. var l1 = lg[p] - 1; // path1 length
  26948. var l2 = lg[p + 1] - 1; // path2 length
  26949. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26950. var shft = idx[1] - idx[0]; // shift
  26951. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26952. while (pi <= min && p < path1nb) {
  26953. // 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
  26954. indices.push(pi, pi + shft, pi + 1);
  26955. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26956. pi += 1;
  26957. if (pi === min) {
  26958. p++;
  26959. if (p === lg.length - 1) {
  26960. shft = idx[0] - idx[p];
  26961. l1 = lg[p] - 1;
  26962. l2 = lg[0] - 1;
  26963. }
  26964. else {
  26965. shft = idx[p + 1] - idx[p];
  26966. l1 = lg[p] - 1;
  26967. l2 = lg[p + 1] - 1;
  26968. }
  26969. pi = idx[p];
  26970. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26971. }
  26972. }
  26973. // normals
  26974. VertexData.ComputeNormals(positions, indices, normals);
  26975. if (closePath) {
  26976. var indexFirst = 0;
  26977. var indexLast = 0;
  26978. for (p = 0; p < pathArray.length; p++) {
  26979. indexFirst = idx[p] * 3;
  26980. if (p + 1 < pathArray.length) {
  26981. indexLast = (idx[p + 1] - 1) * 3;
  26982. }
  26983. else {
  26984. indexLast = normals.length - 3;
  26985. }
  26986. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26987. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26988. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26989. normals[indexLast] = normals[indexFirst];
  26990. normals[indexLast + 1] = normals[indexFirst + 1];
  26991. normals[indexLast + 2] = normals[indexFirst + 2];
  26992. }
  26993. }
  26994. // sides
  26995. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26996. // Colors
  26997. if (customColors) {
  26998. var colors = new Float32Array(customColors.length * 4);
  26999. for (var c = 0; c < customColors.length; c++) {
  27000. colors[c * 4] = customColors[c].r;
  27001. colors[c * 4 + 1] = customColors[c].g;
  27002. colors[c * 4 + 2] = customColors[c].b;
  27003. colors[c * 4 + 3] = customColors[c].a;
  27004. }
  27005. }
  27006. // Result
  27007. var vertexData = new VertexData();
  27008. var positions32 = new Float32Array(positions);
  27009. var normals32 = new Float32Array(normals);
  27010. var uvs32 = new Float32Array(uvs);
  27011. vertexData.indices = indices;
  27012. vertexData.positions = positions32;
  27013. vertexData.normals = normals32;
  27014. vertexData.uvs = uvs32;
  27015. if (customColors) {
  27016. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  27017. }
  27018. if (closePath) {
  27019. vertexData._idx = idx;
  27020. }
  27021. return vertexData;
  27022. };
  27023. /**
  27024. * Creates the VertexData of the Box.
  27025. */
  27026. VertexData.CreateBox = function (options) {
  27027. var normalsSource = [
  27028. new BABYLON.Vector3(0, 0, 1),
  27029. new BABYLON.Vector3(0, 0, -1),
  27030. new BABYLON.Vector3(1, 0, 0),
  27031. new BABYLON.Vector3(-1, 0, 0),
  27032. new BABYLON.Vector3(0, 1, 0),
  27033. new BABYLON.Vector3(0, -1, 0)
  27034. ];
  27035. var indices = [];
  27036. var positions = [];
  27037. var normals = [];
  27038. var uvs = [];
  27039. var width = options.width || options.size || 1;
  27040. var height = options.height || options.size || 1;
  27041. var depth = options.depth || options.size || 1;
  27042. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27043. var faceUV = options.faceUV || new Array(6);
  27044. var faceColors = options.faceColors;
  27045. var colors = [];
  27046. // default face colors and UV if undefined
  27047. for (var f = 0; f < 6; f++) {
  27048. if (faceUV[f] === undefined) {
  27049. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27050. }
  27051. if (faceColors && faceColors[f] === undefined) {
  27052. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27053. }
  27054. }
  27055. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27056. // Create each face in turn.
  27057. for (var index = 0; index < normalsSource.length; index++) {
  27058. var normal = normalsSource[index];
  27059. // Get two vectors perpendicular to the face normal and to each other.
  27060. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27061. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27062. // Six indices (two triangles) per face.
  27063. var verticesLength = positions.length / 3;
  27064. indices.push(verticesLength);
  27065. indices.push(verticesLength + 1);
  27066. indices.push(verticesLength + 2);
  27067. indices.push(verticesLength);
  27068. indices.push(verticesLength + 2);
  27069. indices.push(verticesLength + 3);
  27070. // Four vertices per face.
  27071. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27072. positions.push(vertex.x, vertex.y, vertex.z);
  27073. normals.push(normal.x, normal.y, normal.z);
  27074. uvs.push(faceUV[index].z, faceUV[index].w);
  27075. if (faceColors) {
  27076. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27077. }
  27078. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27079. positions.push(vertex.x, vertex.y, vertex.z);
  27080. normals.push(normal.x, normal.y, normal.z);
  27081. uvs.push(faceUV[index].x, faceUV[index].w);
  27082. if (faceColors) {
  27083. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27084. }
  27085. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27086. positions.push(vertex.x, vertex.y, vertex.z);
  27087. normals.push(normal.x, normal.y, normal.z);
  27088. uvs.push(faceUV[index].x, faceUV[index].y);
  27089. if (faceColors) {
  27090. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27091. }
  27092. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27093. positions.push(vertex.x, vertex.y, vertex.z);
  27094. normals.push(normal.x, normal.y, normal.z);
  27095. uvs.push(faceUV[index].z, faceUV[index].y);
  27096. if (faceColors) {
  27097. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27098. }
  27099. }
  27100. // sides
  27101. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27102. // Result
  27103. var vertexData = new VertexData();
  27104. vertexData.indices = indices;
  27105. vertexData.positions = positions;
  27106. vertexData.normals = normals;
  27107. vertexData.uvs = uvs;
  27108. if (faceColors) {
  27109. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27110. vertexData.colors = totalColors;
  27111. }
  27112. return vertexData;
  27113. };
  27114. /**
  27115. * Creates the VertexData of the Sphere.
  27116. */
  27117. VertexData.CreateSphere = function (options) {
  27118. var segments = options.segments || 32;
  27119. var diameterX = options.diameterX || options.diameter || 1;
  27120. var diameterY = options.diameterY || options.diameter || 1;
  27121. var diameterZ = options.diameterZ || options.diameter || 1;
  27122. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27123. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27124. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27125. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27126. var totalZRotationSteps = 2 + segments;
  27127. var totalYRotationSteps = 2 * totalZRotationSteps;
  27128. var indices = [];
  27129. var positions = [];
  27130. var normals = [];
  27131. var uvs = [];
  27132. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27133. var normalizedZ = zRotationStep / totalZRotationSteps;
  27134. var angleZ = normalizedZ * Math.PI * slice;
  27135. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27136. var normalizedY = yRotationStep / totalYRotationSteps;
  27137. var angleY = normalizedY * Math.PI * 2 * arc;
  27138. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27139. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27140. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27141. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27142. var vertex = complete.multiply(radius);
  27143. var normal = complete.divide(radius).normalize();
  27144. positions.push(vertex.x, vertex.y, vertex.z);
  27145. normals.push(normal.x, normal.y, normal.z);
  27146. uvs.push(normalizedY, normalizedZ);
  27147. }
  27148. if (zRotationStep > 0) {
  27149. var verticesCount = positions.length / 3;
  27150. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27151. indices.push((firstIndex));
  27152. indices.push((firstIndex + 1));
  27153. indices.push(firstIndex + totalYRotationSteps + 1);
  27154. indices.push((firstIndex + totalYRotationSteps + 1));
  27155. indices.push((firstIndex + 1));
  27156. indices.push((firstIndex + totalYRotationSteps + 2));
  27157. }
  27158. }
  27159. }
  27160. // Sides
  27161. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27162. // Result
  27163. var vertexData = new VertexData();
  27164. vertexData.indices = indices;
  27165. vertexData.positions = positions;
  27166. vertexData.normals = normals;
  27167. vertexData.uvs = uvs;
  27168. return vertexData;
  27169. };
  27170. /**
  27171. * Creates the VertexData of the Cylinder or Cone.
  27172. */
  27173. VertexData.CreateCylinder = function (options) {
  27174. var height = options.height || 2;
  27175. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27176. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27177. var tessellation = options.tessellation || 24;
  27178. var subdivisions = options.subdivisions || 1;
  27179. var hasRings = options.hasRings;
  27180. var enclose = options.enclose;
  27181. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27182. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27183. var faceUV = options.faceUV || new Array(3);
  27184. var faceColors = options.faceColors;
  27185. // default face colors and UV if undefined
  27186. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27187. var ringNb = (hasRings) ? subdivisions : 1;
  27188. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27189. var f;
  27190. for (f = 0; f < surfaceNb; f++) {
  27191. if (faceColors && faceColors[f] === undefined) {
  27192. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27193. }
  27194. }
  27195. for (f = 0; f < surfaceNb; f++) {
  27196. if (faceUV && faceUV[f] === undefined) {
  27197. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27198. }
  27199. }
  27200. var indices = [];
  27201. var positions = [];
  27202. var normals = [];
  27203. var uvs = [];
  27204. var colors = [];
  27205. var angle_step = Math.PI * 2 * arc / tessellation;
  27206. var angle;
  27207. var h;
  27208. var radius;
  27209. var tan = (diameterBottom - diameterTop) / 2 / height;
  27210. var ringVertex = BABYLON.Vector3.Zero();
  27211. var ringNormal = BABYLON.Vector3.Zero();
  27212. var ringFirstVertex = BABYLON.Vector3.Zero();
  27213. var ringFirstNormal = BABYLON.Vector3.Zero();
  27214. var quadNormal = BABYLON.Vector3.Zero();
  27215. var Y = BABYLON.Axis.Y;
  27216. // positions, normals, uvs
  27217. var i;
  27218. var j;
  27219. var r;
  27220. var ringIdx = 1;
  27221. var s = 1; // surface index
  27222. var cs = 0;
  27223. var v = 0;
  27224. for (i = 0; i <= subdivisions; i++) {
  27225. h = i / subdivisions;
  27226. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27227. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27228. for (r = 0; r < ringIdx; r++) {
  27229. if (hasRings) {
  27230. s += r;
  27231. }
  27232. if (enclose) {
  27233. s += 2 * r;
  27234. }
  27235. for (j = 0; j <= tessellation; j++) {
  27236. angle = j * angle_step;
  27237. // position
  27238. ringVertex.x = Math.cos(-angle) * radius;
  27239. ringVertex.y = -height / 2 + h * height;
  27240. ringVertex.z = Math.sin(-angle) * radius;
  27241. // normal
  27242. if (diameterTop === 0 && i === subdivisions) {
  27243. // if no top cap, reuse former normals
  27244. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27245. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27246. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27247. }
  27248. else {
  27249. ringNormal.x = ringVertex.x;
  27250. ringNormal.z = ringVertex.z;
  27251. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27252. ringNormal.normalize();
  27253. }
  27254. // keep first ring vertex values for enclose
  27255. if (j === 0) {
  27256. ringFirstVertex.copyFrom(ringVertex);
  27257. ringFirstNormal.copyFrom(ringNormal);
  27258. }
  27259. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27260. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27261. if (hasRings) {
  27262. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27263. }
  27264. else {
  27265. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27266. }
  27267. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27268. if (faceColors) {
  27269. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27270. }
  27271. }
  27272. // if enclose, add four vertices and their dedicated normals
  27273. if (arc !== 1 && enclose) {
  27274. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27275. positions.push(0, ringVertex.y, 0);
  27276. positions.push(0, ringVertex.y, 0);
  27277. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27278. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27279. quadNormal.normalize();
  27280. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27281. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27282. quadNormal.normalize();
  27283. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27284. if (hasRings) {
  27285. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27286. }
  27287. else {
  27288. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27289. }
  27290. uvs.push(faceUV[s + 1].x, v);
  27291. uvs.push(faceUV[s + 1].z, v);
  27292. if (hasRings) {
  27293. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27294. }
  27295. else {
  27296. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27297. }
  27298. uvs.push(faceUV[s + 2].x, v);
  27299. uvs.push(faceUV[s + 2].z, v);
  27300. if (faceColors) {
  27301. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27302. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27303. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27304. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27305. }
  27306. }
  27307. if (cs !== s) {
  27308. cs = s;
  27309. }
  27310. }
  27311. }
  27312. // indices
  27313. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27314. var s;
  27315. i = 0;
  27316. for (s = 0; s < subdivisions; s++) {
  27317. for (j = 0; j < tessellation; j++) {
  27318. var i0 = i * (e + 1) + j;
  27319. var i1 = (i + 1) * (e + 1) + j;
  27320. var i2 = i * (e + 1) + (j + 1);
  27321. var i3 = (i + 1) * (e + 1) + (j + 1);
  27322. indices.push(i0, i1, i2);
  27323. indices.push(i3, i2, i1);
  27324. }
  27325. if (arc !== 1 && enclose) {
  27326. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27327. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27328. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27329. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27330. }
  27331. i = (hasRings) ? (i + 2) : (i + 1);
  27332. }
  27333. // Caps
  27334. var createCylinderCap = function (isTop) {
  27335. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27336. if (radius === 0) {
  27337. return;
  27338. }
  27339. // Cap positions, normals & uvs
  27340. var angle;
  27341. var circleVector;
  27342. var i;
  27343. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27344. var c;
  27345. if (faceColors) {
  27346. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27347. }
  27348. // cap center
  27349. var vbase = positions.length / 3;
  27350. var offset = isTop ? height / 2 : -height / 2;
  27351. var center = new BABYLON.Vector3(0, offset, 0);
  27352. positions.push(center.x, center.y, center.z);
  27353. normals.push(0, isTop ? 1 : -1, 0);
  27354. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27355. if (faceColors) {
  27356. colors.push(c.r, c.g, c.b, c.a);
  27357. }
  27358. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27359. for (i = 0; i <= tessellation; i++) {
  27360. angle = Math.PI * 2 * i * arc / tessellation;
  27361. var cos = Math.cos(-angle);
  27362. var sin = Math.sin(-angle);
  27363. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27364. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27365. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27366. normals.push(0, isTop ? 1 : -1, 0);
  27367. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27368. if (faceColors) {
  27369. colors.push(c.r, c.g, c.b, c.a);
  27370. }
  27371. }
  27372. // Cap indices
  27373. for (i = 0; i < tessellation; i++) {
  27374. if (!isTop) {
  27375. indices.push(vbase);
  27376. indices.push(vbase + (i + 1));
  27377. indices.push(vbase + (i + 2));
  27378. }
  27379. else {
  27380. indices.push(vbase);
  27381. indices.push(vbase + (i + 2));
  27382. indices.push(vbase + (i + 1));
  27383. }
  27384. }
  27385. };
  27386. // add caps to geometry
  27387. createCylinderCap(false);
  27388. createCylinderCap(true);
  27389. // Sides
  27390. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27391. var vertexData = new VertexData();
  27392. vertexData.indices = indices;
  27393. vertexData.positions = positions;
  27394. vertexData.normals = normals;
  27395. vertexData.uvs = uvs;
  27396. if (faceColors) {
  27397. vertexData.colors = colors;
  27398. }
  27399. return vertexData;
  27400. };
  27401. /**
  27402. * Creates the VertexData of the Torus.
  27403. */
  27404. VertexData.CreateTorus = function (options) {
  27405. var indices = [];
  27406. var positions = [];
  27407. var normals = [];
  27408. var uvs = [];
  27409. var diameter = options.diameter || 1;
  27410. var thickness = options.thickness || 0.5;
  27411. var tessellation = options.tessellation || 16;
  27412. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27413. var stride = tessellation + 1;
  27414. for (var i = 0; i <= tessellation; i++) {
  27415. var u = i / tessellation;
  27416. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27417. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27418. for (var j = 0; j <= tessellation; j++) {
  27419. var v = 1 - j / tessellation;
  27420. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27421. var dx = Math.cos(innerAngle);
  27422. var dy = Math.sin(innerAngle);
  27423. // Create a vertex.
  27424. var normal = new BABYLON.Vector3(dx, dy, 0);
  27425. var position = normal.scale(thickness / 2);
  27426. var textureCoordinate = new BABYLON.Vector2(u, v);
  27427. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27428. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27429. positions.push(position.x, position.y, position.z);
  27430. normals.push(normal.x, normal.y, normal.z);
  27431. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27432. // And create indices for two triangles.
  27433. var nextI = (i + 1) % stride;
  27434. var nextJ = (j + 1) % stride;
  27435. indices.push(i * stride + j);
  27436. indices.push(i * stride + nextJ);
  27437. indices.push(nextI * stride + j);
  27438. indices.push(i * stride + nextJ);
  27439. indices.push(nextI * stride + nextJ);
  27440. indices.push(nextI * stride + j);
  27441. }
  27442. }
  27443. // Sides
  27444. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27445. // Result
  27446. var vertexData = new VertexData();
  27447. vertexData.indices = indices;
  27448. vertexData.positions = positions;
  27449. vertexData.normals = normals;
  27450. vertexData.uvs = uvs;
  27451. return vertexData;
  27452. };
  27453. /**
  27454. * Creates the VertexData of the LineSystem.
  27455. */
  27456. VertexData.CreateLineSystem = function (options) {
  27457. var indices = [];
  27458. var positions = [];
  27459. var lines = options.lines;
  27460. var idx = 0;
  27461. for (var l = 0; l < lines.length; l++) {
  27462. var points = lines[l];
  27463. for (var index = 0; index < points.length; index++) {
  27464. positions.push(points[index].x, points[index].y, points[index].z);
  27465. if (index > 0) {
  27466. indices.push(idx - 1);
  27467. indices.push(idx);
  27468. }
  27469. idx++;
  27470. }
  27471. }
  27472. var vertexData = new VertexData();
  27473. vertexData.indices = indices;
  27474. vertexData.positions = positions;
  27475. return vertexData;
  27476. };
  27477. /**
  27478. * Create the VertexData of the DashedLines.
  27479. */
  27480. VertexData.CreateDashedLines = function (options) {
  27481. var dashSize = options.dashSize || 3;
  27482. var gapSize = options.gapSize || 1;
  27483. var dashNb = options.dashNb || 200;
  27484. var points = options.points;
  27485. var positions = new Array();
  27486. var indices = new Array();
  27487. var curvect = BABYLON.Vector3.Zero();
  27488. var lg = 0;
  27489. var nb = 0;
  27490. var shft = 0;
  27491. var dashshft = 0;
  27492. var curshft = 0;
  27493. var idx = 0;
  27494. var i = 0;
  27495. for (i = 0; i < points.length - 1; i++) {
  27496. points[i + 1].subtractToRef(points[i], curvect);
  27497. lg += curvect.length();
  27498. }
  27499. shft = lg / dashNb;
  27500. dashshft = dashSize * shft / (dashSize + gapSize);
  27501. for (i = 0; i < points.length - 1; i++) {
  27502. points[i + 1].subtractToRef(points[i], curvect);
  27503. nb = Math.floor(curvect.length() / shft);
  27504. curvect.normalize();
  27505. for (var j = 0; j < nb; j++) {
  27506. curshft = shft * j;
  27507. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27508. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27509. indices.push(idx, idx + 1);
  27510. idx += 2;
  27511. }
  27512. }
  27513. // Result
  27514. var vertexData = new VertexData();
  27515. vertexData.positions = positions;
  27516. vertexData.indices = indices;
  27517. return vertexData;
  27518. };
  27519. /**
  27520. * Creates the VertexData of the Ground.
  27521. */
  27522. VertexData.CreateGround = function (options) {
  27523. var indices = [];
  27524. var positions = [];
  27525. var normals = [];
  27526. var uvs = [];
  27527. var row, col;
  27528. var width = options.width || 1;
  27529. var height = options.height || 1;
  27530. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27531. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27532. for (row = 0; row <= subdivisionsY; row++) {
  27533. for (col = 0; col <= subdivisionsX; col++) {
  27534. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27535. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27536. positions.push(position.x, position.y, position.z);
  27537. normals.push(normal.x, normal.y, normal.z);
  27538. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27539. }
  27540. }
  27541. for (row = 0; row < subdivisionsY; row++) {
  27542. for (col = 0; col < subdivisionsX; col++) {
  27543. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27544. indices.push(col + 1 + row * (subdivisionsX + 1));
  27545. indices.push(col + row * (subdivisionsX + 1));
  27546. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27547. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27548. indices.push(col + row * (subdivisionsX + 1));
  27549. }
  27550. }
  27551. // Result
  27552. var vertexData = new VertexData();
  27553. vertexData.indices = indices;
  27554. vertexData.positions = positions;
  27555. vertexData.normals = normals;
  27556. vertexData.uvs = uvs;
  27557. return vertexData;
  27558. };
  27559. /**
  27560. * Creates the VertexData of the TiledGround.
  27561. */
  27562. VertexData.CreateTiledGround = function (options) {
  27563. var xmin = options.xmin || -1.0;
  27564. var zmin = options.zmin || -1.0;
  27565. var xmax = options.xmax || 1.0;
  27566. var zmax = options.zmax || 1.0;
  27567. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27568. var precision = options.precision || { w: 1, h: 1 };
  27569. var indices = [];
  27570. var positions = [];
  27571. var normals = [];
  27572. var uvs = [];
  27573. var row, col, tileRow, tileCol;
  27574. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27575. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27576. precision.w = (precision.w < 1) ? 1 : precision.w;
  27577. precision.h = (precision.h < 1) ? 1 : precision.h;
  27578. var tileSize = {
  27579. 'w': (xmax - xmin) / subdivisions.w,
  27580. 'h': (zmax - zmin) / subdivisions.h
  27581. };
  27582. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27583. // Indices
  27584. var base = positions.length / 3;
  27585. var rowLength = precision.w + 1;
  27586. for (row = 0; row < precision.h; row++) {
  27587. for (col = 0; col < precision.w; col++) {
  27588. var square = [
  27589. base + col + row * rowLength,
  27590. base + (col + 1) + row * rowLength,
  27591. base + (col + 1) + (row + 1) * rowLength,
  27592. base + col + (row + 1) * rowLength
  27593. ];
  27594. indices.push(square[1]);
  27595. indices.push(square[2]);
  27596. indices.push(square[3]);
  27597. indices.push(square[0]);
  27598. indices.push(square[1]);
  27599. indices.push(square[3]);
  27600. }
  27601. }
  27602. // Position, normals and uvs
  27603. var position = BABYLON.Vector3.Zero();
  27604. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27605. for (row = 0; row <= precision.h; row++) {
  27606. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27607. for (col = 0; col <= precision.w; col++) {
  27608. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27609. position.y = 0;
  27610. positions.push(position.x, position.y, position.z);
  27611. normals.push(normal.x, normal.y, normal.z);
  27612. uvs.push(col / precision.w, row / precision.h);
  27613. }
  27614. }
  27615. }
  27616. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27617. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27618. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27619. }
  27620. }
  27621. // Result
  27622. var vertexData = new VertexData();
  27623. vertexData.indices = indices;
  27624. vertexData.positions = positions;
  27625. vertexData.normals = normals;
  27626. vertexData.uvs = uvs;
  27627. return vertexData;
  27628. };
  27629. /**
  27630. * Creates the VertexData of the Ground designed from a heightmap.
  27631. */
  27632. VertexData.CreateGroundFromHeightMap = function (options) {
  27633. var indices = [];
  27634. var positions = [];
  27635. var normals = [];
  27636. var uvs = [];
  27637. var row, col;
  27638. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27639. // Vertices
  27640. for (row = 0; row <= options.subdivisions; row++) {
  27641. for (col = 0; col <= options.subdivisions; col++) {
  27642. 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));
  27643. // Compute height
  27644. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27645. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27646. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27647. var r = options.buffer[pos] / 255.0;
  27648. var g = options.buffer[pos + 1] / 255.0;
  27649. var b = options.buffer[pos + 2] / 255.0;
  27650. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27651. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27652. // Add vertex
  27653. positions.push(position.x, position.y, position.z);
  27654. normals.push(0, 0, 0);
  27655. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27656. }
  27657. }
  27658. // Indices
  27659. for (row = 0; row < options.subdivisions; row++) {
  27660. for (col = 0; col < options.subdivisions; col++) {
  27661. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27662. indices.push(col + 1 + row * (options.subdivisions + 1));
  27663. indices.push(col + row * (options.subdivisions + 1));
  27664. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27665. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27666. indices.push(col + row * (options.subdivisions + 1));
  27667. }
  27668. }
  27669. // Normals
  27670. VertexData.ComputeNormals(positions, indices, normals);
  27671. // Result
  27672. var vertexData = new VertexData();
  27673. vertexData.indices = indices;
  27674. vertexData.positions = positions;
  27675. vertexData.normals = normals;
  27676. vertexData.uvs = uvs;
  27677. return vertexData;
  27678. };
  27679. /**
  27680. * Creates the VertexData of the Plane.
  27681. */
  27682. VertexData.CreatePlane = function (options) {
  27683. var indices = [];
  27684. var positions = [];
  27685. var normals = [];
  27686. var uvs = [];
  27687. var width = options.width || options.size || 1;
  27688. var height = options.height || options.size || 1;
  27689. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27690. // Vertices
  27691. var halfWidth = width / 2.0;
  27692. var halfHeight = height / 2.0;
  27693. positions.push(-halfWidth, -halfHeight, 0);
  27694. normals.push(0, 0, -1.0);
  27695. uvs.push(0.0, 0.0);
  27696. positions.push(halfWidth, -halfHeight, 0);
  27697. normals.push(0, 0, -1.0);
  27698. uvs.push(1.0, 0.0);
  27699. positions.push(halfWidth, halfHeight, 0);
  27700. normals.push(0, 0, -1.0);
  27701. uvs.push(1.0, 1.0);
  27702. positions.push(-halfWidth, halfHeight, 0);
  27703. normals.push(0, 0, -1.0);
  27704. uvs.push(0.0, 1.0);
  27705. // Indices
  27706. indices.push(0);
  27707. indices.push(1);
  27708. indices.push(2);
  27709. indices.push(0);
  27710. indices.push(2);
  27711. indices.push(3);
  27712. // Sides
  27713. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27714. // Result
  27715. var vertexData = new VertexData();
  27716. vertexData.indices = indices;
  27717. vertexData.positions = positions;
  27718. vertexData.normals = normals;
  27719. vertexData.uvs = uvs;
  27720. return vertexData;
  27721. };
  27722. /**
  27723. * Creates the VertexData of the Disc or regular Polygon.
  27724. */
  27725. VertexData.CreateDisc = function (options) {
  27726. var positions = [];
  27727. var indices = [];
  27728. var normals = [];
  27729. var uvs = [];
  27730. var radius = options.radius || 0.5;
  27731. var tessellation = options.tessellation || 64;
  27732. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27733. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27734. // positions and uvs
  27735. positions.push(0, 0, 0); // disc center first
  27736. uvs.push(0.5, 0.5);
  27737. var theta = Math.PI * 2 * arc;
  27738. var step = theta / tessellation;
  27739. for (var a = 0; a < theta; a += step) {
  27740. var x = Math.cos(a);
  27741. var y = Math.sin(a);
  27742. var u = (x + 1) / 2;
  27743. var v = (1 - y) / 2;
  27744. positions.push(radius * x, radius * y, 0);
  27745. uvs.push(u, v);
  27746. }
  27747. if (arc === 1) {
  27748. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27749. uvs.push(uvs[2], uvs[3]);
  27750. }
  27751. //indices
  27752. var vertexNb = positions.length / 3;
  27753. for (var i = 1; i < vertexNb - 1; i++) {
  27754. indices.push(i + 1, 0, i);
  27755. }
  27756. // result
  27757. VertexData.ComputeNormals(positions, indices, normals);
  27758. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27759. var vertexData = new VertexData();
  27760. vertexData.indices = indices;
  27761. vertexData.positions = positions;
  27762. vertexData.normals = normals;
  27763. vertexData.uvs = uvs;
  27764. return vertexData;
  27765. };
  27766. /**
  27767. * Re-creates the VertexData of the Polygon for sideOrientation.
  27768. */
  27769. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  27770. var faceUV = fUV || new Array(3);
  27771. var faceColors = fColors;
  27772. var colors = [];
  27773. // default face colors and UV if undefined
  27774. for (var f = 0; f < 3; f++) {
  27775. if (faceUV[f] === undefined) {
  27776. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27777. }
  27778. if (faceColors && faceColors[f] === undefined) {
  27779. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27780. }
  27781. }
  27782. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27783. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27784. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27785. var indices = polygon.getIndices();
  27786. // set face colours and textures
  27787. var idx = 0;
  27788. var face = 0;
  27789. for (var index = 0; index < normals.length; index += 3) {
  27790. //Edge Face no. 1
  27791. if (Math.abs(normals[index + 1]) < 0.001) {
  27792. face = 1;
  27793. }
  27794. //Top Face no. 0
  27795. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  27796. face = 0;
  27797. }
  27798. //Bottom Face no. 2
  27799. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  27800. face = 2;
  27801. }
  27802. idx = index / 3;
  27803. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  27804. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  27805. if (faceColors) {
  27806. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  27807. }
  27808. }
  27809. // sides
  27810. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  27811. // Result
  27812. var vertexData = new VertexData();
  27813. vertexData.indices = indices;
  27814. vertexData.positions = positions;
  27815. vertexData.normals = normals;
  27816. vertexData.uvs = uvs;
  27817. if (faceColors) {
  27818. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27819. vertexData.colors = totalColors;
  27820. }
  27821. return vertexData;
  27822. };
  27823. /**
  27824. * Creates the VertexData of the IcoSphere.
  27825. */
  27826. VertexData.CreateIcoSphere = function (options) {
  27827. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27828. var radius = options.radius || 1;
  27829. var flat = (options.flat === undefined) ? true : options.flat;
  27830. var subdivisions = options.subdivisions || 4;
  27831. var radiusX = options.radiusX || radius;
  27832. var radiusY = options.radiusY || radius;
  27833. var radiusZ = options.radiusZ || radius;
  27834. var t = (1 + Math.sqrt(5)) / 2;
  27835. // 12 vertex x,y,z
  27836. var ico_vertices = [
  27837. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27838. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27839. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27840. ];
  27841. // index of 3 vertex makes a face of icopshere
  27842. var ico_indices = [
  27843. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27844. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27845. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27846. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27847. ];
  27848. // vertex for uv have aliased position, not for UV
  27849. var vertices_unalias_id = [
  27850. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27851. // vertex alias
  27852. 0,
  27853. 2,
  27854. 3,
  27855. 3,
  27856. 3,
  27857. 4,
  27858. 7,
  27859. 8,
  27860. 9,
  27861. 9,
  27862. 10,
  27863. 11 // 23: B + 12
  27864. ];
  27865. // uv as integer step (not pixels !)
  27866. var ico_vertexuv = [
  27867. 5, 1, 3, 1, 6, 4, 0, 0,
  27868. 5, 3, 4, 2, 2, 2, 4, 0,
  27869. 2, 0, 1, 1, 6, 0, 6, 2,
  27870. // vertex alias (for same vertex on different faces)
  27871. 0, 4,
  27872. 3, 3,
  27873. 4, 4,
  27874. 3, 1,
  27875. 4, 2,
  27876. 4, 4,
  27877. 0, 2,
  27878. 1, 1,
  27879. 2, 2,
  27880. 3, 3,
  27881. 1, 3,
  27882. 2, 4 // 23: B + 12
  27883. ];
  27884. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27885. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27886. // First island of uv mapping
  27887. // v = 4h 3+ 2
  27888. // v = 3h 9+ 4
  27889. // v = 2h 9+ 5 B
  27890. // v = 1h 9 1 0
  27891. // v = 0h 3 8 7 A
  27892. // u = 0 1 2 3 4 5 6 *a
  27893. // Second island of uv mapping
  27894. // v = 4h 0+ B+ 4+
  27895. // v = 3h A+ 2+
  27896. // v = 2h 7+ 6 3+
  27897. // v = 1h 8+ 3+
  27898. // v = 0h
  27899. // u = 0 1 2 3 4 5 6 *a
  27900. // Face layout on texture UV mapping
  27901. // ============
  27902. // \ 4 /\ 16 / ======
  27903. // \ / \ / /\ 11 /
  27904. // \/ 7 \/ / \ /
  27905. // ======= / 10 \/
  27906. // /\ 17 /\ =======
  27907. // / \ / \ \ 15 /\
  27908. // / 8 \/ 12 \ \ / \
  27909. // ============ \/ 6 \
  27910. // \ 18 /\ ============
  27911. // \ / \ \ 5 /\ 0 /
  27912. // \/ 13 \ \ / \ /
  27913. // ======= \/ 1 \/
  27914. // =============
  27915. // /\ 19 /\ 2 /\
  27916. // / \ / \ / \
  27917. // / 14 \/ 9 \/ 3 \
  27918. // ===================
  27919. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27920. var ustep = 138 / 1024;
  27921. var vstep = 239 / 1024;
  27922. var uoffset = 60 / 1024;
  27923. var voffset = 26 / 1024;
  27924. // Second island should have margin, not to touch the first island
  27925. // avoid any borderline artefact in pixel rounding
  27926. var island_u_offset = -40 / 1024;
  27927. var island_v_offset = +20 / 1024;
  27928. // face is either island 0 or 1 :
  27929. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27930. var island = [
  27931. 0, 0, 0, 0, 1,
  27932. 0, 0, 1, 1, 0,
  27933. 0, 0, 1, 1, 0,
  27934. 0, 1, 1, 1, 0 // 15 - 19
  27935. ];
  27936. var indices = [];
  27937. var positions = [];
  27938. var normals = [];
  27939. var uvs = [];
  27940. var current_indice = 0;
  27941. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27942. var face_vertex_pos = new Array(3);
  27943. var face_vertex_uv = new Array(3);
  27944. var v012;
  27945. for (v012 = 0; v012 < 3; v012++) {
  27946. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27947. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27948. }
  27949. // create all with normals
  27950. for (var face = 0; face < 20; face++) {
  27951. // 3 vertex per face
  27952. for (v012 = 0; v012 < 3; v012++) {
  27953. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27954. var v_id = ico_indices[3 * face + v012];
  27955. // vertex have 3D position (x,y,z)
  27956. 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]);
  27957. // Normalize to get normal, then scale to radius
  27958. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27959. // uv Coordinates from vertex ID
  27960. 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);
  27961. }
  27962. // Subdivide the face (interpolate pos, norm, uv)
  27963. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27964. // - norm is linear interpolation of vertex corner normal
  27965. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27966. // - uv is linear interpolation
  27967. //
  27968. // Topology is as below for sub-divide by 2
  27969. // vertex shown as v0,v1,v2
  27970. // interp index is i1 to progress in range [v0,v1[
  27971. // interp index is i2 to progress in range [v0,v2[
  27972. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27973. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27974. //
  27975. //
  27976. // i2 v2
  27977. // ^ ^
  27978. // / / \
  27979. // / / \
  27980. // / / \
  27981. // / / (0,1) \
  27982. // / #---------\
  27983. // / / \ (0,0)'/ \
  27984. // / / \ / \
  27985. // / / \ / \
  27986. // / / (0,0) \ / (1,0) \
  27987. // / #---------#---------\
  27988. // v0 v1
  27989. //
  27990. // --------------------> i1
  27991. //
  27992. // interp of (i1,i2):
  27993. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27994. // along i1 : lerp(x0,x1, i1/(S-i2))
  27995. //
  27996. // centroid of triangle is needed to get help normal computation
  27997. // (c1,c2) are used for centroid location
  27998. var interp_vertex = function (i1, i2, c1, c2) {
  27999. // vertex is interpolated from
  28000. // - face_vertex_pos[0..2]
  28001. // - face_vertex_uv[0..2]
  28002. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28003. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28004. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28005. pos_interp.normalize();
  28006. var vertex_normal;
  28007. if (flat) {
  28008. // in flat mode, recalculate normal as face centroid normal
  28009. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28010. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28011. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28012. }
  28013. else {
  28014. // in smooth mode, recalculate normal from each single vertex position
  28015. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28016. }
  28017. // Vertex normal need correction due to X,Y,Z radius scaling
  28018. vertex_normal.x /= radiusX;
  28019. vertex_normal.y /= radiusY;
  28020. vertex_normal.z /= radiusZ;
  28021. vertex_normal.normalize();
  28022. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28023. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28024. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28025. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28026. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28027. uvs.push(uv_interp.x, uv_interp.y);
  28028. // push each vertex has member of a face
  28029. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28030. indices.push(current_indice);
  28031. current_indice++;
  28032. };
  28033. for (var i2 = 0; i2 < subdivisions; i2++) {
  28034. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28035. // face : (i1,i2) for /\ :
  28036. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28037. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28038. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28039. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28040. if (i1 + i2 + 1 < subdivisions) {
  28041. // face : (i1,i2)' for \/ :
  28042. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28043. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28044. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28045. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28046. }
  28047. }
  28048. }
  28049. }
  28050. // Sides
  28051. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28052. // Result
  28053. var vertexData = new VertexData();
  28054. vertexData.indices = indices;
  28055. vertexData.positions = positions;
  28056. vertexData.normals = normals;
  28057. vertexData.uvs = uvs;
  28058. return vertexData;
  28059. };
  28060. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28061. /**
  28062. * Creates the VertexData of the Polyhedron.
  28063. */
  28064. VertexData.CreatePolyhedron = function (options) {
  28065. // provided polyhedron types :
  28066. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28067. // 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)
  28068. var polyhedra = [];
  28069. 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]] };
  28070. 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]] };
  28071. polyhedra[2] = {
  28072. 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]],
  28073. 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]]
  28074. };
  28075. polyhedra[3] = {
  28076. 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]],
  28077. 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]]
  28078. };
  28079. polyhedra[4] = {
  28080. 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]],
  28081. 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]]
  28082. };
  28083. 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]] };
  28084. 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]] };
  28085. 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]] };
  28086. 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]] };
  28087. 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]] };
  28088. 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]] };
  28089. 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]] };
  28090. 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]] };
  28091. 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]] };
  28092. polyhedra[14] = {
  28093. 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]],
  28094. 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]]
  28095. };
  28096. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28097. var size = options.size;
  28098. var sizeX = options.sizeX || size || 1;
  28099. var sizeY = options.sizeY || size || 1;
  28100. var sizeZ = options.sizeZ || size || 1;
  28101. var data = options.custom || polyhedra[type];
  28102. var nbfaces = data.face.length;
  28103. var faceUV = options.faceUV || new Array(nbfaces);
  28104. var faceColors = options.faceColors;
  28105. var flat = (options.flat === undefined) ? true : options.flat;
  28106. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28107. var positions = [];
  28108. var indices = [];
  28109. var normals = [];
  28110. var uvs = [];
  28111. var colors = [];
  28112. var index = 0;
  28113. var faceIdx = 0; // face cursor in the array "indexes"
  28114. var indexes = [];
  28115. var i = 0;
  28116. var f = 0;
  28117. var u, v, ang, x, y, tmp;
  28118. // default face colors and UV if undefined
  28119. if (flat) {
  28120. for (f = 0; f < nbfaces; f++) {
  28121. if (faceColors && faceColors[f] === undefined) {
  28122. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28123. }
  28124. if (faceUV && faceUV[f] === undefined) {
  28125. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28126. }
  28127. }
  28128. }
  28129. if (!flat) {
  28130. for (i = 0; i < data.vertex.length; i++) {
  28131. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28132. uvs.push(0, 0);
  28133. }
  28134. for (f = 0; f < nbfaces; f++) {
  28135. for (i = 0; i < data.face[f].length - 2; i++) {
  28136. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28137. }
  28138. }
  28139. }
  28140. else {
  28141. for (f = 0; f < nbfaces; f++) {
  28142. var fl = data.face[f].length; // number of vertices of the current face
  28143. ang = 2 * Math.PI / fl;
  28144. x = 0.5 * Math.tan(ang / 2);
  28145. y = 0.5;
  28146. // positions, uvs, colors
  28147. for (i = 0; i < fl; i++) {
  28148. // positions
  28149. 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);
  28150. indexes.push(index);
  28151. index++;
  28152. // uvs
  28153. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28154. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28155. uvs.push(u, v);
  28156. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28157. y = x * Math.sin(ang) + y * Math.cos(ang);
  28158. x = tmp;
  28159. // colors
  28160. if (faceColors) {
  28161. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28162. }
  28163. }
  28164. // indices from indexes
  28165. for (i = 0; i < fl - 2; i++) {
  28166. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28167. }
  28168. faceIdx += fl;
  28169. }
  28170. }
  28171. VertexData.ComputeNormals(positions, indices, normals);
  28172. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28173. var vertexData = new VertexData();
  28174. vertexData.positions = positions;
  28175. vertexData.indices = indices;
  28176. vertexData.normals = normals;
  28177. vertexData.uvs = uvs;
  28178. if (faceColors && flat) {
  28179. vertexData.colors = colors;
  28180. }
  28181. return vertexData;
  28182. };
  28183. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28184. /**
  28185. * Creates the VertexData of the Torus Knot.
  28186. */
  28187. VertexData.CreateTorusKnot = function (options) {
  28188. var indices = [];
  28189. var positions = [];
  28190. var normals = [];
  28191. var uvs = [];
  28192. var radius = options.radius || 2;
  28193. var tube = options.tube || 0.5;
  28194. var radialSegments = options.radialSegments || 32;
  28195. var tubularSegments = options.tubularSegments || 32;
  28196. var p = options.p || 2;
  28197. var q = options.q || 3;
  28198. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28199. // Helper
  28200. var getPos = function (angle) {
  28201. var cu = Math.cos(angle);
  28202. var su = Math.sin(angle);
  28203. var quOverP = q / p * angle;
  28204. var cs = Math.cos(quOverP);
  28205. var tx = radius * (2 + cs) * 0.5 * cu;
  28206. var ty = radius * (2 + cs) * su * 0.5;
  28207. var tz = radius * Math.sin(quOverP) * 0.5;
  28208. return new BABYLON.Vector3(tx, ty, tz);
  28209. };
  28210. // Vertices
  28211. var i;
  28212. var j;
  28213. for (i = 0; i <= radialSegments; i++) {
  28214. var modI = i % radialSegments;
  28215. var u = modI / radialSegments * 2 * p * Math.PI;
  28216. var p1 = getPos(u);
  28217. var p2 = getPos(u + 0.01);
  28218. var tang = p2.subtract(p1);
  28219. var n = p2.add(p1);
  28220. var bitan = BABYLON.Vector3.Cross(tang, n);
  28221. n = BABYLON.Vector3.Cross(bitan, tang);
  28222. bitan.normalize();
  28223. n.normalize();
  28224. for (j = 0; j < tubularSegments; j++) {
  28225. var modJ = j % tubularSegments;
  28226. var v = modJ / tubularSegments * 2 * Math.PI;
  28227. var cx = -tube * Math.cos(v);
  28228. var cy = tube * Math.sin(v);
  28229. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28230. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28231. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28232. uvs.push(i / radialSegments);
  28233. uvs.push(j / tubularSegments);
  28234. }
  28235. }
  28236. for (i = 0; i < radialSegments; i++) {
  28237. for (j = 0; j < tubularSegments; j++) {
  28238. var jNext = (j + 1) % tubularSegments;
  28239. var a = i * tubularSegments + j;
  28240. var b = (i + 1) * tubularSegments + j;
  28241. var c = (i + 1) * tubularSegments + jNext;
  28242. var d = i * tubularSegments + jNext;
  28243. indices.push(d);
  28244. indices.push(b);
  28245. indices.push(a);
  28246. indices.push(d);
  28247. indices.push(c);
  28248. indices.push(b);
  28249. }
  28250. }
  28251. // Normals
  28252. VertexData.ComputeNormals(positions, indices, normals);
  28253. // Sides
  28254. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28255. // Result
  28256. var vertexData = new VertexData();
  28257. vertexData.indices = indices;
  28258. vertexData.positions = positions;
  28259. vertexData.normals = normals;
  28260. vertexData.uvs = uvs;
  28261. return vertexData;
  28262. };
  28263. // Tools
  28264. /**
  28265. * @param {any} - positions (number[] or Float32Array)
  28266. * @param {any} - indices (number[] or Uint16Array)
  28267. * @param {any} - normals (number[] or Float32Array)
  28268. * options (optional) :
  28269. * facetPositions : optional array of facet positions (vector3)
  28270. * facetNormals : optional array of facet normals (vector3)
  28271. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28272. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28273. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28274. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28275. * bInfo : optional bounding info, required for facetPartitioning computation
  28276. */
  28277. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28278. // temporary scalar variables
  28279. var index = 0; // facet index
  28280. var p1p2x = 0.0; // p1p2 vector x coordinate
  28281. var p1p2y = 0.0; // p1p2 vector y coordinate
  28282. var p1p2z = 0.0; // p1p2 vector z coordinate
  28283. var p3p2x = 0.0; // p3p2 vector x coordinate
  28284. var p3p2y = 0.0; // p3p2 vector y coordinate
  28285. var p3p2z = 0.0; // p3p2 vector z coordinate
  28286. var faceNormalx = 0.0; // facet normal x coordinate
  28287. var faceNormaly = 0.0; // facet normal y coordinate
  28288. var faceNormalz = 0.0; // facet normal z coordinate
  28289. var length = 0.0; // facet normal length before normalization
  28290. var v1x = 0; // vector1 x index in the positions array
  28291. var v1y = 0; // vector1 y index in the positions array
  28292. var v1z = 0; // vector1 z index in the positions array
  28293. var v2x = 0; // vector2 x index in the positions array
  28294. var v2y = 0; // vector2 y index in the positions array
  28295. var v2z = 0; // vector2 z index in the positions array
  28296. var v3x = 0; // vector3 x index in the positions array
  28297. var v3y = 0; // vector3 y index in the positions array
  28298. var v3z = 0; // vector3 z index in the positions array
  28299. var computeFacetNormals = false;
  28300. var computeFacetPositions = false;
  28301. var computeFacetPartitioning = false;
  28302. var faceNormalSign = 1;
  28303. if (options) {
  28304. computeFacetNormals = (options.facetNormals) ? true : false;
  28305. computeFacetPositions = (options.facetPositions) ? true : false;
  28306. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28307. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28308. }
  28309. // facetPartitioning reinit if needed
  28310. if (computeFacetPartitioning) {
  28311. var ox = 0; // X partitioning index for facet position
  28312. var oy = 0; // Y partinioning index for facet position
  28313. var oz = 0; // Z partinioning index for facet position
  28314. var b1x = 0; // X partitioning index for facet v1 vertex
  28315. var b1y = 0; // Y partitioning index for facet v1 vertex
  28316. var b1z = 0; // z partitioning index for facet v1 vertex
  28317. var b2x = 0; // X partitioning index for facet v2 vertex
  28318. var b2y = 0; // Y partitioning index for facet v2 vertex
  28319. var b2z = 0; // Z partitioning index for facet v2 vertex
  28320. var b3x = 0; // X partitioning index for facet v3 vertex
  28321. var b3y = 0; // Y partitioning index for facet v3 vertex
  28322. var b3z = 0; // Z partitioning index for facet v3 vertex
  28323. var block_idx_o = 0; // facet barycenter block index
  28324. var block_idx_v1 = 0; // v1 vertex block index
  28325. var block_idx_v2 = 0; // v2 vertex block index
  28326. var block_idx_v3 = 0; // v3 vertex block index
  28327. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28328. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28329. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28330. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28331. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28332. var subSq = options.subDiv.max * options.subDiv.max;
  28333. options.facetPartitioning.length = 0;
  28334. }
  28335. // reset the normals
  28336. for (index = 0; index < positions.length; index++) {
  28337. normals[index] = 0.0;
  28338. }
  28339. // Loop : 1 indice triplet = 1 facet
  28340. var nbFaces = indices.length / 3;
  28341. for (index = 0; index < nbFaces; index++) {
  28342. // get the indexes of the coordinates of each vertex of the facet
  28343. v1x = indices[index * 3] * 3;
  28344. v1y = v1x + 1;
  28345. v1z = v1x + 2;
  28346. v2x = indices[index * 3 + 1] * 3;
  28347. v2y = v2x + 1;
  28348. v2z = v2x + 2;
  28349. v3x = indices[index * 3 + 2] * 3;
  28350. v3y = v3x + 1;
  28351. v3z = v3x + 2;
  28352. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28353. p1p2y = positions[v1y] - positions[v2y];
  28354. p1p2z = positions[v1z] - positions[v2z];
  28355. p3p2x = positions[v3x] - positions[v2x];
  28356. p3p2y = positions[v3y] - positions[v2y];
  28357. p3p2z = positions[v3z] - positions[v2z];
  28358. // compute the face normal with the cross product
  28359. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28360. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28361. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28362. // normalize this normal and store it in the array facetData
  28363. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28364. length = (length === 0) ? 1.0 : length;
  28365. faceNormalx /= length;
  28366. faceNormaly /= length;
  28367. faceNormalz /= length;
  28368. if (computeFacetNormals) {
  28369. options.facetNormals[index].x = faceNormalx;
  28370. options.facetNormals[index].y = faceNormaly;
  28371. options.facetNormals[index].z = faceNormalz;
  28372. }
  28373. if (computeFacetPositions) {
  28374. // compute and the facet barycenter coordinates in the array facetPositions
  28375. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28376. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28377. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28378. }
  28379. if (computeFacetPartitioning) {
  28380. // store the facet indexes in arrays in the main facetPartitioning array :
  28381. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28382. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28383. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28384. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28385. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28386. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28387. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28388. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28389. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28390. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28391. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28392. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28393. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28394. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28395. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28396. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28397. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28398. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28399. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28400. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28401. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28402. // push each facet index in each block containing the vertex
  28403. options.facetPartitioning[block_idx_v1].push(index);
  28404. if (block_idx_v2 != block_idx_v1) {
  28405. options.facetPartitioning[block_idx_v2].push(index);
  28406. }
  28407. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28408. options.facetPartitioning[block_idx_v3].push(index);
  28409. }
  28410. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28411. options.facetPartitioning[block_idx_o].push(index);
  28412. }
  28413. }
  28414. // compute the normals anyway
  28415. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28416. normals[v1y] += faceNormaly;
  28417. normals[v1z] += faceNormalz;
  28418. normals[v2x] += faceNormalx;
  28419. normals[v2y] += faceNormaly;
  28420. normals[v2z] += faceNormalz;
  28421. normals[v3x] += faceNormalx;
  28422. normals[v3y] += faceNormaly;
  28423. normals[v3z] += faceNormalz;
  28424. }
  28425. // last normalization of each normal
  28426. for (index = 0; index < normals.length / 3; index++) {
  28427. faceNormalx = normals[index * 3];
  28428. faceNormaly = normals[index * 3 + 1];
  28429. faceNormalz = normals[index * 3 + 2];
  28430. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28431. length = (length === 0) ? 1.0 : length;
  28432. faceNormalx /= length;
  28433. faceNormaly /= length;
  28434. faceNormalz /= length;
  28435. normals[index * 3] = faceNormalx;
  28436. normals[index * 3 + 1] = faceNormaly;
  28437. normals[index * 3 + 2] = faceNormalz;
  28438. }
  28439. };
  28440. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28441. var li = indices.length;
  28442. var ln = normals.length;
  28443. var i;
  28444. var n;
  28445. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28446. switch (sideOrientation) {
  28447. case BABYLON.Mesh.FRONTSIDE:
  28448. // nothing changed
  28449. break;
  28450. case BABYLON.Mesh.BACKSIDE:
  28451. var tmp;
  28452. // indices
  28453. for (i = 0; i < li; i += 3) {
  28454. tmp = indices[i];
  28455. indices[i] = indices[i + 2];
  28456. indices[i + 2] = tmp;
  28457. }
  28458. // normals
  28459. for (n = 0; n < ln; n++) {
  28460. normals[n] = -normals[n];
  28461. }
  28462. break;
  28463. case BABYLON.Mesh.DOUBLESIDE:
  28464. // positions
  28465. var lp = positions.length;
  28466. var l = lp / 3;
  28467. for (var p = 0; p < lp; p++) {
  28468. positions[lp + p] = positions[p];
  28469. }
  28470. // indices
  28471. for (i = 0; i < li; i += 3) {
  28472. indices[i + li] = indices[i + 2] + l;
  28473. indices[i + 1 + li] = indices[i + 1] + l;
  28474. indices[i + 2 + li] = indices[i] + l;
  28475. }
  28476. // normals
  28477. for (n = 0; n < ln; n++) {
  28478. normals[ln + n] = -normals[n];
  28479. }
  28480. // uvs
  28481. var lu = uvs.length;
  28482. var u = 0;
  28483. for (u = 0; u < lu; u++) {
  28484. uvs[u + lu] = uvs[u];
  28485. }
  28486. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28487. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28488. u = 0;
  28489. for (i = 0; i < lu / 2; i++) {
  28490. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28491. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28492. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28493. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28494. u += 2;
  28495. }
  28496. break;
  28497. }
  28498. };
  28499. /**
  28500. * Creates a new VertexData from the imported parameters.
  28501. */
  28502. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28503. var vertexData = new VertexData();
  28504. // positions
  28505. var positions = parsedVertexData.positions;
  28506. if (positions) {
  28507. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28508. }
  28509. // normals
  28510. var normals = parsedVertexData.normals;
  28511. if (normals) {
  28512. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28513. }
  28514. // tangents
  28515. var tangents = parsedVertexData.tangents;
  28516. if (tangents) {
  28517. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28518. }
  28519. // uvs
  28520. var uvs = parsedVertexData.uvs;
  28521. if (uvs) {
  28522. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28523. }
  28524. // uv2s
  28525. var uv2s = parsedVertexData.uv2s;
  28526. if (uv2s) {
  28527. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28528. }
  28529. // uv3s
  28530. var uv3s = parsedVertexData.uv3s;
  28531. if (uv3s) {
  28532. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28533. }
  28534. // uv4s
  28535. var uv4s = parsedVertexData.uv4s;
  28536. if (uv4s) {
  28537. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28538. }
  28539. // uv5s
  28540. var uv5s = parsedVertexData.uv5s;
  28541. if (uv5s) {
  28542. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28543. }
  28544. // uv6s
  28545. var uv6s = parsedVertexData.uv6s;
  28546. if (uv6s) {
  28547. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28548. }
  28549. // colors
  28550. var colors = parsedVertexData.colors;
  28551. if (colors) {
  28552. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28553. }
  28554. // matricesIndices
  28555. var matricesIndices = parsedVertexData.matricesIndices;
  28556. if (matricesIndices) {
  28557. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28558. }
  28559. // matricesWeights
  28560. var matricesWeights = parsedVertexData.matricesWeights;
  28561. if (matricesWeights) {
  28562. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28563. }
  28564. // indices
  28565. var indices = parsedVertexData.indices;
  28566. if (indices) {
  28567. vertexData.indices = indices;
  28568. }
  28569. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28570. };
  28571. return VertexData;
  28572. }());
  28573. BABYLON.VertexData = VertexData;
  28574. })(BABYLON || (BABYLON = {}));
  28575. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28576. var BABYLON;
  28577. (function (BABYLON) {
  28578. var Geometry = (function () {
  28579. function Geometry(id, scene, vertexData, updatable, mesh) {
  28580. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28581. this._totalVertices = 0;
  28582. this._isDisposed = false;
  28583. this.id = id;
  28584. this._engine = scene.getEngine();
  28585. this._meshes = [];
  28586. this._scene = scene;
  28587. //Init vertex buffer cache
  28588. this._vertexBuffers = {};
  28589. this._indices = [];
  28590. this._updatable = updatable;
  28591. // vertexData
  28592. if (vertexData) {
  28593. this.setAllVerticesData(vertexData, updatable);
  28594. }
  28595. else {
  28596. this._totalVertices = 0;
  28597. this._indices = [];
  28598. }
  28599. if (this._engine.getCaps().vertexArrayObject) {
  28600. this._vertexArrayObjects = {};
  28601. }
  28602. // applyToMesh
  28603. if (mesh) {
  28604. if (mesh.getClassName() === "LinesMesh") {
  28605. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28606. this.updateExtend();
  28607. }
  28608. this.applyToMesh(mesh);
  28609. mesh.computeWorldMatrix(true);
  28610. }
  28611. }
  28612. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28613. /**
  28614. * 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
  28615. * @returns The Bias Vector
  28616. */
  28617. get: function () {
  28618. return this._boundingBias;
  28619. },
  28620. set: function (value) {
  28621. if (this._boundingBias && this._boundingBias.equals(value)) {
  28622. return;
  28623. }
  28624. this._boundingBias = value.clone();
  28625. this.updateBoundingInfo(true, null);
  28626. },
  28627. enumerable: true,
  28628. configurable: true
  28629. });
  28630. Object.defineProperty(Geometry.prototype, "extend", {
  28631. get: function () {
  28632. return this._extend;
  28633. },
  28634. enumerable: true,
  28635. configurable: true
  28636. });
  28637. Geometry.prototype.getScene = function () {
  28638. return this._scene;
  28639. };
  28640. Geometry.prototype.getEngine = function () {
  28641. return this._engine;
  28642. };
  28643. Geometry.prototype.isReady = function () {
  28644. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28645. };
  28646. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28647. get: function () {
  28648. for (var index = 0; index < this._meshes.length; index++) {
  28649. if (!this._meshes[index].doNotSerialize) {
  28650. return false;
  28651. }
  28652. }
  28653. return true;
  28654. },
  28655. enumerable: true,
  28656. configurable: true
  28657. });
  28658. Geometry.prototype._rebuild = function () {
  28659. if (this._vertexArrayObjects) {
  28660. this._vertexArrayObjects = {};
  28661. }
  28662. // Index buffer
  28663. if (this._meshes.length !== 0 && this._indices) {
  28664. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28665. }
  28666. // Vertex buffers
  28667. for (var key in this._vertexBuffers) {
  28668. var vertexBuffer = this._vertexBuffers[key];
  28669. vertexBuffer._rebuild();
  28670. }
  28671. };
  28672. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28673. vertexData.applyToGeometry(this, updatable);
  28674. this.notifyUpdate();
  28675. };
  28676. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28677. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28678. this.setVerticesBuffer(buffer);
  28679. };
  28680. Geometry.prototype.removeVerticesData = function (kind) {
  28681. if (this._vertexBuffers[kind]) {
  28682. this._vertexBuffers[kind].dispose();
  28683. delete this._vertexBuffers[kind];
  28684. }
  28685. };
  28686. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28687. var kind = buffer.getKind();
  28688. if (this._vertexBuffers[kind]) {
  28689. this._vertexBuffers[kind].dispose();
  28690. }
  28691. this._vertexBuffers[kind] = buffer;
  28692. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28693. var data = buffer.getData();
  28694. var stride = buffer.getStrideSize();
  28695. this._totalVertices = data.length / stride;
  28696. this.updateExtend(data, stride);
  28697. this._resetPointsArrayCache();
  28698. var meshes = this._meshes;
  28699. var numOfMeshes = meshes.length;
  28700. for (var index = 0; index < numOfMeshes; index++) {
  28701. var mesh = meshes[index];
  28702. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28703. mesh._createGlobalSubMesh(false);
  28704. mesh.computeWorldMatrix(true);
  28705. }
  28706. }
  28707. this.notifyUpdate(kind);
  28708. if (this._vertexArrayObjects) {
  28709. this._disposeVertexArrayObjects();
  28710. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28711. }
  28712. };
  28713. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28714. var vertexBuffer = this.getVertexBuffer(kind);
  28715. if (!vertexBuffer) {
  28716. return;
  28717. }
  28718. vertexBuffer.updateDirectly(data, offset);
  28719. this.notifyUpdate(kind);
  28720. };
  28721. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28722. var vertexBuffer = this.getVertexBuffer(kind);
  28723. if (!vertexBuffer) {
  28724. return;
  28725. }
  28726. vertexBuffer.update(data);
  28727. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28728. var stride = vertexBuffer.getStrideSize();
  28729. this._totalVertices = data.length / stride;
  28730. this.updateBoundingInfo(updateExtends, data);
  28731. }
  28732. this.notifyUpdate(kind);
  28733. };
  28734. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28735. if (updateExtends) {
  28736. this.updateExtend(data);
  28737. }
  28738. var meshes = this._meshes;
  28739. var numOfMeshes = meshes.length;
  28740. this._resetPointsArrayCache();
  28741. for (var index = 0; index < numOfMeshes; index++) {
  28742. var mesh = meshes[index];
  28743. if (updateExtends) {
  28744. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28745. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28746. var subMesh = mesh.subMeshes[subIndex];
  28747. subMesh.refreshBoundingInfo();
  28748. }
  28749. }
  28750. }
  28751. };
  28752. Geometry.prototype._bind = function (effect, indexToBind) {
  28753. if (indexToBind === void 0) { indexToBind = undefined; }
  28754. if (indexToBind === undefined) {
  28755. indexToBind = this._indexBuffer;
  28756. }
  28757. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  28758. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  28759. return;
  28760. }
  28761. // Using VAO
  28762. if (!this._vertexArrayObjects[effect.key]) {
  28763. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  28764. }
  28765. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  28766. };
  28767. Geometry.prototype.getTotalVertices = function () {
  28768. if (!this.isReady()) {
  28769. return 0;
  28770. }
  28771. return this._totalVertices;
  28772. };
  28773. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28774. var vertexBuffer = this.getVertexBuffer(kind);
  28775. if (!vertexBuffer) {
  28776. return null;
  28777. }
  28778. var orig = vertexBuffer.getData();
  28779. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  28780. return orig;
  28781. }
  28782. else {
  28783. var len = orig.length;
  28784. var copy = [];
  28785. for (var i = 0; i < len; i++) {
  28786. copy.push(orig[i]);
  28787. }
  28788. return copy;
  28789. }
  28790. };
  28791. Geometry.prototype.getVertexBuffer = function (kind) {
  28792. if (!this.isReady()) {
  28793. return null;
  28794. }
  28795. return this._vertexBuffers[kind];
  28796. };
  28797. Geometry.prototype.getVertexBuffers = function () {
  28798. if (!this.isReady()) {
  28799. return null;
  28800. }
  28801. return this._vertexBuffers;
  28802. };
  28803. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28804. if (!this._vertexBuffers) {
  28805. if (this._delayInfo) {
  28806. return this._delayInfo.indexOf(kind) !== -1;
  28807. }
  28808. return false;
  28809. }
  28810. return this._vertexBuffers[kind] !== undefined;
  28811. };
  28812. Geometry.prototype.getVerticesDataKinds = function () {
  28813. var result = [];
  28814. var kind;
  28815. if (!this._vertexBuffers && this._delayInfo) {
  28816. for (kind in this._delayInfo) {
  28817. result.push(kind);
  28818. }
  28819. }
  28820. else {
  28821. for (kind in this._vertexBuffers) {
  28822. result.push(kind);
  28823. }
  28824. }
  28825. return result;
  28826. };
  28827. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28828. if (this._indexBuffer) {
  28829. this._engine._releaseBuffer(this._indexBuffer);
  28830. }
  28831. this._disposeVertexArrayObjects();
  28832. this._indices = indices;
  28833. if (this._meshes.length !== 0 && this._indices) {
  28834. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28835. }
  28836. if (totalVertices !== undefined) {
  28837. this._totalVertices = totalVertices;
  28838. }
  28839. var meshes = this._meshes;
  28840. var numOfMeshes = meshes.length;
  28841. for (var index = 0; index < numOfMeshes; index++) {
  28842. meshes[index]._createGlobalSubMesh(true);
  28843. }
  28844. this.notifyUpdate();
  28845. };
  28846. Geometry.prototype.getTotalIndices = function () {
  28847. if (!this.isReady()) {
  28848. return 0;
  28849. }
  28850. return this._indices.length;
  28851. };
  28852. Geometry.prototype.getIndices = function (copyWhenShared) {
  28853. if (!this.isReady()) {
  28854. return null;
  28855. }
  28856. var orig = this._indices;
  28857. if (!copyWhenShared || this._meshes.length === 1) {
  28858. return orig;
  28859. }
  28860. else {
  28861. var len = orig.length;
  28862. var copy = [];
  28863. for (var i = 0; i < len; i++) {
  28864. copy.push(orig[i]);
  28865. }
  28866. return copy;
  28867. }
  28868. };
  28869. Geometry.prototype.getIndexBuffer = function () {
  28870. if (!this.isReady()) {
  28871. return null;
  28872. }
  28873. return this._indexBuffer;
  28874. };
  28875. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  28876. if (!effect || !this._vertexArrayObjects) {
  28877. return;
  28878. }
  28879. if (this._vertexArrayObjects[effect.key]) {
  28880. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  28881. delete this._vertexArrayObjects[effect.key];
  28882. }
  28883. };
  28884. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28885. var meshes = this._meshes;
  28886. var index = meshes.indexOf(mesh);
  28887. if (index === -1) {
  28888. return;
  28889. }
  28890. meshes.splice(index, 1);
  28891. mesh._geometry = null;
  28892. if (meshes.length === 0 && shouldDispose) {
  28893. this.dispose();
  28894. }
  28895. };
  28896. Geometry.prototype.applyToMesh = function (mesh) {
  28897. if (mesh._geometry === this) {
  28898. return;
  28899. }
  28900. var previousGeometry = mesh._geometry;
  28901. if (previousGeometry) {
  28902. previousGeometry.releaseForMesh(mesh);
  28903. }
  28904. var meshes = this._meshes;
  28905. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28906. mesh._geometry = this;
  28907. this._scene.pushGeometry(this);
  28908. meshes.push(mesh);
  28909. if (this.isReady()) {
  28910. this._applyToMesh(mesh);
  28911. }
  28912. else {
  28913. mesh._boundingInfo = this._boundingInfo;
  28914. }
  28915. };
  28916. Geometry.prototype.updateExtend = function (data, stride) {
  28917. if (data === void 0) { data = null; }
  28918. if (!data) {
  28919. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  28920. }
  28921. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  28922. };
  28923. Geometry.prototype._applyToMesh = function (mesh) {
  28924. var numOfMeshes = this._meshes.length;
  28925. // vertexBuffers
  28926. for (var kind in this._vertexBuffers) {
  28927. if (numOfMeshes === 1) {
  28928. this._vertexBuffers[kind].create();
  28929. }
  28930. var buffer = this._vertexBuffers[kind].getBuffer();
  28931. if (buffer)
  28932. buffer.references = numOfMeshes;
  28933. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28934. if (!this._extend) {
  28935. this.updateExtend(this._vertexBuffers[kind].getData());
  28936. }
  28937. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28938. mesh._createGlobalSubMesh(false);
  28939. //bounding info was just created again, world matrix should be applied again.
  28940. mesh._updateBoundingInfo();
  28941. }
  28942. }
  28943. // indexBuffer
  28944. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  28945. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28946. }
  28947. if (this._indexBuffer) {
  28948. this._indexBuffer.references = numOfMeshes;
  28949. }
  28950. };
  28951. Geometry.prototype.notifyUpdate = function (kind) {
  28952. if (this.onGeometryUpdated) {
  28953. this.onGeometryUpdated(this, kind);
  28954. }
  28955. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  28956. var mesh = _a[_i];
  28957. mesh._markSubMeshesAsAttributesDirty();
  28958. }
  28959. };
  28960. Geometry.prototype.load = function (scene, onLoaded) {
  28961. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28962. return;
  28963. }
  28964. if (this.isReady()) {
  28965. if (onLoaded) {
  28966. onLoaded();
  28967. }
  28968. return;
  28969. }
  28970. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28971. this._queueLoad(scene, onLoaded);
  28972. };
  28973. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  28974. var _this = this;
  28975. scene._addPendingData(this);
  28976. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28977. _this._delayLoadingFunction(JSON.parse(data), _this);
  28978. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28979. _this._delayInfo = [];
  28980. scene._removePendingData(_this);
  28981. var meshes = _this._meshes;
  28982. var numOfMeshes = meshes.length;
  28983. for (var index = 0; index < numOfMeshes; index++) {
  28984. _this._applyToMesh(meshes[index]);
  28985. }
  28986. if (onLoaded) {
  28987. onLoaded();
  28988. }
  28989. }, function () { }, scene.database);
  28990. };
  28991. /**
  28992. * Invert the geometry to move from a right handed system to a left handed one.
  28993. */
  28994. Geometry.prototype.toLeftHanded = function () {
  28995. // Flip faces
  28996. var tIndices = this.getIndices(false);
  28997. if (tIndices != null && tIndices.length > 0) {
  28998. for (var i = 0; i < tIndices.length; i += 3) {
  28999. var tTemp = tIndices[i + 0];
  29000. tIndices[i + 0] = tIndices[i + 2];
  29001. tIndices[i + 2] = tTemp;
  29002. }
  29003. this.setIndices(tIndices);
  29004. }
  29005. // Negate position.z
  29006. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  29007. if (tPositions != null && tPositions.length > 0) {
  29008. for (var i = 0; i < tPositions.length; i += 3) {
  29009. tPositions[i + 2] = -tPositions[i + 2];
  29010. }
  29011. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  29012. }
  29013. // Negate normal.z
  29014. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  29015. if (tNormals != null && tNormals.length > 0) {
  29016. for (var i = 0; i < tNormals.length; i += 3) {
  29017. tNormals[i + 2] = -tNormals[i + 2];
  29018. }
  29019. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  29020. }
  29021. };
  29022. // Cache
  29023. Geometry.prototype._resetPointsArrayCache = function () {
  29024. this._positions = null;
  29025. };
  29026. Geometry.prototype._generatePointsArray = function () {
  29027. if (this._positions)
  29028. return true;
  29029. this._positions = [];
  29030. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29031. if (!data) {
  29032. return false;
  29033. }
  29034. for (var index = 0; index < data.length; index += 3) {
  29035. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  29036. }
  29037. return true;
  29038. };
  29039. Geometry.prototype.isDisposed = function () {
  29040. return this._isDisposed;
  29041. };
  29042. Geometry.prototype._disposeVertexArrayObjects = function () {
  29043. if (this._vertexArrayObjects) {
  29044. for (var kind in this._vertexArrayObjects) {
  29045. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  29046. }
  29047. this._vertexArrayObjects = {};
  29048. }
  29049. };
  29050. Geometry.prototype.dispose = function () {
  29051. var meshes = this._meshes;
  29052. var numOfMeshes = meshes.length;
  29053. var index;
  29054. for (index = 0; index < numOfMeshes; index++) {
  29055. this.releaseForMesh(meshes[index]);
  29056. }
  29057. this._meshes = [];
  29058. this._disposeVertexArrayObjects();
  29059. for (var kind in this._vertexBuffers) {
  29060. this._vertexBuffers[kind].dispose();
  29061. }
  29062. this._vertexBuffers = {};
  29063. this._totalVertices = 0;
  29064. if (this._indexBuffer) {
  29065. this._engine._releaseBuffer(this._indexBuffer);
  29066. }
  29067. this._indexBuffer = null;
  29068. this._indices = [];
  29069. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29070. this.delayLoadingFile = null;
  29071. this._delayLoadingFunction = null;
  29072. this._delayInfo = [];
  29073. this._boundingInfo = null;
  29074. this._scene.removeGeometry(this);
  29075. this._isDisposed = true;
  29076. };
  29077. Geometry.prototype.copy = function (id) {
  29078. var vertexData = new BABYLON.VertexData();
  29079. vertexData.indices = [];
  29080. var indices = this.getIndices();
  29081. for (var index = 0; index < indices.length; index++) {
  29082. vertexData.indices.push(indices[index]);
  29083. }
  29084. var updatable = false;
  29085. var stopChecking = false;
  29086. var kind;
  29087. for (kind in this._vertexBuffers) {
  29088. // using slice() to make a copy of the array and not just reference it
  29089. var data = this.getVerticesData(kind);
  29090. if (data instanceof Float32Array) {
  29091. vertexData.set(new Float32Array(data), kind);
  29092. }
  29093. else {
  29094. vertexData.set(data.slice(0), kind);
  29095. }
  29096. if (!stopChecking) {
  29097. updatable = this.getVertexBuffer(kind).isUpdatable();
  29098. stopChecking = !updatable;
  29099. }
  29100. }
  29101. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29102. geometry.delayLoadState = this.delayLoadState;
  29103. geometry.delayLoadingFile = this.delayLoadingFile;
  29104. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29105. for (kind in this._delayInfo) {
  29106. geometry._delayInfo = geometry._delayInfo || [];
  29107. geometry._delayInfo.push(kind);
  29108. }
  29109. // Bounding info
  29110. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29111. return geometry;
  29112. };
  29113. Geometry.prototype.serialize = function () {
  29114. var serializationObject = {};
  29115. serializationObject.id = this.id;
  29116. serializationObject.updatable = this._updatable;
  29117. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29118. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29119. }
  29120. return serializationObject;
  29121. };
  29122. Geometry.prototype.toNumberArray = function (origin) {
  29123. if (Array.isArray(origin)) {
  29124. return origin;
  29125. }
  29126. else {
  29127. return Array.prototype.slice.call(origin);
  29128. }
  29129. };
  29130. Geometry.prototype.serializeVerticeData = function () {
  29131. var serializationObject = this.serialize();
  29132. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29133. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  29134. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  29135. serializationObject.positions._updatable = true;
  29136. }
  29137. }
  29138. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29139. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  29140. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  29141. serializationObject.normals._updatable = true;
  29142. }
  29143. }
  29144. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29145. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  29146. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  29147. serializationObject.uvs._updatable = true;
  29148. }
  29149. }
  29150. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29151. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  29152. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  29153. serializationObject.uv2s._updatable = true;
  29154. }
  29155. }
  29156. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29157. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  29158. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  29159. serializationObject.uv3s._updatable = true;
  29160. }
  29161. }
  29162. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29163. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  29164. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  29165. serializationObject.uv4s._updatable = true;
  29166. }
  29167. }
  29168. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29169. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  29170. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  29171. serializationObject.uv5s._updatable = true;
  29172. }
  29173. }
  29174. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29175. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29176. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29177. serializationObject.uv6s._updatable = true;
  29178. }
  29179. }
  29180. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29181. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29182. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29183. serializationObject.colors._updatable = true;
  29184. }
  29185. }
  29186. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29187. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29188. serializationObject.matricesIndices._isExpanded = true;
  29189. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29190. serializationObject.matricesIndices._updatable = true;
  29191. }
  29192. }
  29193. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29194. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29195. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29196. serializationObject.matricesWeights._updatable = true;
  29197. }
  29198. }
  29199. serializationObject.indices = this.toNumberArray(this.getIndices());
  29200. return serializationObject;
  29201. };
  29202. // Statics
  29203. Geometry.ExtractFromMesh = function (mesh, id) {
  29204. var geometry = mesh._geometry;
  29205. if (!geometry) {
  29206. return null;
  29207. }
  29208. return geometry.copy(id);
  29209. };
  29210. /**
  29211. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29212. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29213. * Be aware Math.random() could cause collisions, but:
  29214. * "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"
  29215. */
  29216. Geometry.RandomId = function () {
  29217. return BABYLON.Tools.RandomId();
  29218. };
  29219. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29220. var scene = mesh.getScene();
  29221. // Geometry
  29222. var geometryId = parsedGeometry.geometryId;
  29223. if (geometryId) {
  29224. var geometry = scene.getGeometryByID(geometryId);
  29225. if (geometry) {
  29226. geometry.applyToMesh(mesh);
  29227. }
  29228. }
  29229. else if (parsedGeometry instanceof ArrayBuffer) {
  29230. var binaryInfo = mesh._binaryInfo;
  29231. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29232. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29233. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29234. }
  29235. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29236. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29237. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29238. }
  29239. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29240. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29241. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29242. }
  29243. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29244. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29245. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29246. }
  29247. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29248. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29249. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29250. }
  29251. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29252. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29253. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29254. }
  29255. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29256. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29257. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29258. }
  29259. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29260. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29261. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29262. }
  29263. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29264. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29265. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29266. }
  29267. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29268. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29269. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29270. }
  29271. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29272. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29273. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29274. }
  29275. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29276. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29277. mesh.setIndices(indicesData);
  29278. }
  29279. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29280. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29281. mesh.subMeshes = [];
  29282. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29283. var materialIndex = subMeshesData[(i * 5) + 0];
  29284. var verticesStart = subMeshesData[(i * 5) + 1];
  29285. var verticesCount = subMeshesData[(i * 5) + 2];
  29286. var indexStart = subMeshesData[(i * 5) + 3];
  29287. var indexCount = subMeshesData[(i * 5) + 4];
  29288. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29289. }
  29290. }
  29291. }
  29292. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29293. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29294. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29295. if (parsedGeometry.uvs) {
  29296. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29297. }
  29298. if (parsedGeometry.uvs2) {
  29299. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29300. }
  29301. if (parsedGeometry.uvs3) {
  29302. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29303. }
  29304. if (parsedGeometry.uvs4) {
  29305. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29306. }
  29307. if (parsedGeometry.uvs5) {
  29308. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29309. }
  29310. if (parsedGeometry.uvs6) {
  29311. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29312. }
  29313. if (parsedGeometry.colors) {
  29314. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29315. }
  29316. if (parsedGeometry.matricesIndices) {
  29317. if (!parsedGeometry.matricesIndices._isExpanded) {
  29318. var floatIndices = [];
  29319. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29320. var matricesIndex = parsedGeometry.matricesIndices[i];
  29321. floatIndices.push(matricesIndex & 0x000000FF);
  29322. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29323. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29324. floatIndices.push(matricesIndex >> 24);
  29325. }
  29326. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29327. }
  29328. else {
  29329. delete parsedGeometry.matricesIndices._isExpanded;
  29330. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29331. }
  29332. }
  29333. if (parsedGeometry.matricesIndicesExtra) {
  29334. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29335. var floatIndices = [];
  29336. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29337. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29338. floatIndices.push(matricesIndex & 0x000000FF);
  29339. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29340. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29341. floatIndices.push(matricesIndex >> 24);
  29342. }
  29343. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29344. }
  29345. else {
  29346. delete parsedGeometry.matricesIndices._isExpanded;
  29347. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29348. }
  29349. }
  29350. if (parsedGeometry.matricesWeights) {
  29351. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  29352. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29353. }
  29354. if (parsedGeometry.matricesWeightsExtra) {
  29355. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  29356. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29357. }
  29358. mesh.setIndices(parsedGeometry.indices);
  29359. }
  29360. // SubMeshes
  29361. if (parsedGeometry.subMeshes) {
  29362. mesh.subMeshes = [];
  29363. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29364. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29365. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29366. }
  29367. }
  29368. // Flat shading
  29369. if (mesh._shouldGenerateFlatShading) {
  29370. mesh.convertToFlatShadedMesh();
  29371. delete mesh._shouldGenerateFlatShading;
  29372. }
  29373. // Update
  29374. mesh.computeWorldMatrix(true);
  29375. // Octree
  29376. if (scene['_selectionOctree']) {
  29377. scene['_selectionOctree'].addMesh(mesh);
  29378. }
  29379. };
  29380. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  29381. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29382. return;
  29383. }
  29384. var size = matricesWeights.length;
  29385. for (var i = 0; i < size; i += influencers) {
  29386. var weight = 0;
  29387. var biggerIndex = i;
  29388. var biggerWeight = 0;
  29389. for (var j = 0; j < influencers - 1; j++) {
  29390. weight += matricesWeights[i + j];
  29391. if (matricesWeights[i + j] > biggerWeight) {
  29392. biggerWeight = matricesWeights[i + j];
  29393. biggerIndex = i + j;
  29394. }
  29395. }
  29396. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  29397. }
  29398. };
  29399. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29400. if (scene.getGeometryByID(parsedVertexData.id)) {
  29401. return null; // null since geometry could be something else than a box...
  29402. }
  29403. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29404. if (BABYLON.Tags) {
  29405. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29406. }
  29407. if (parsedVertexData.delayLoadingFile) {
  29408. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29409. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29410. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29411. geometry._delayInfo = [];
  29412. if (parsedVertexData.hasUVs) {
  29413. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29414. }
  29415. if (parsedVertexData.hasUVs2) {
  29416. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29417. }
  29418. if (parsedVertexData.hasUVs3) {
  29419. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29420. }
  29421. if (parsedVertexData.hasUVs4) {
  29422. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29423. }
  29424. if (parsedVertexData.hasUVs5) {
  29425. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29426. }
  29427. if (parsedVertexData.hasUVs6) {
  29428. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29429. }
  29430. if (parsedVertexData.hasColors) {
  29431. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29432. }
  29433. if (parsedVertexData.hasMatricesIndices) {
  29434. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29435. }
  29436. if (parsedVertexData.hasMatricesWeights) {
  29437. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29438. }
  29439. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29440. }
  29441. else {
  29442. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29443. }
  29444. scene.pushGeometry(geometry, true);
  29445. return geometry;
  29446. };
  29447. return Geometry;
  29448. }());
  29449. BABYLON.Geometry = Geometry;
  29450. /////// Primitives //////////////////////////////////////////////
  29451. (function (Geometry) {
  29452. var Primitives;
  29453. (function (Primitives) {
  29454. /// Abstract class
  29455. var _Primitive = (function (_super) {
  29456. __extends(_Primitive, _super);
  29457. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29458. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29459. _this._canBeRegenerated = _canBeRegenerated;
  29460. _this._beingRegenerated = true;
  29461. _this.regenerate();
  29462. _this._beingRegenerated = false;
  29463. return _this;
  29464. }
  29465. _Primitive.prototype.canBeRegenerated = function () {
  29466. return this._canBeRegenerated;
  29467. };
  29468. _Primitive.prototype.regenerate = function () {
  29469. if (!this._canBeRegenerated) {
  29470. return;
  29471. }
  29472. this._beingRegenerated = true;
  29473. this.setAllVerticesData(this._regenerateVertexData(), false);
  29474. this._beingRegenerated = false;
  29475. };
  29476. _Primitive.prototype.asNewGeometry = function (id) {
  29477. return _super.prototype.copy.call(this, id);
  29478. };
  29479. // overrides
  29480. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29481. if (!this._beingRegenerated) {
  29482. return;
  29483. }
  29484. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29485. };
  29486. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29487. if (!this._beingRegenerated) {
  29488. return;
  29489. }
  29490. _super.prototype.setVerticesData.call(this, kind, data, false);
  29491. };
  29492. // to override
  29493. // protected
  29494. _Primitive.prototype._regenerateVertexData = function () {
  29495. throw new Error("Abstract method");
  29496. };
  29497. _Primitive.prototype.copy = function (id) {
  29498. throw new Error("Must be overriden in sub-classes.");
  29499. };
  29500. _Primitive.prototype.serialize = function () {
  29501. var serializationObject = _super.prototype.serialize.call(this);
  29502. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29503. return serializationObject;
  29504. };
  29505. return _Primitive;
  29506. }(Geometry));
  29507. Primitives._Primitive = _Primitive;
  29508. var Ribbon = (function (_super) {
  29509. __extends(Ribbon, _super);
  29510. // Members
  29511. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29512. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29513. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29514. _this.pathArray = pathArray;
  29515. _this.closeArray = closeArray;
  29516. _this.closePath = closePath;
  29517. _this.offset = offset;
  29518. _this.side = side;
  29519. return _this;
  29520. }
  29521. Ribbon.prototype._regenerateVertexData = function () {
  29522. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29523. };
  29524. Ribbon.prototype.copy = function (id) {
  29525. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29526. };
  29527. return Ribbon;
  29528. }(_Primitive));
  29529. Primitives.Ribbon = Ribbon;
  29530. var Box = (function (_super) {
  29531. __extends(Box, _super);
  29532. // Members
  29533. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29534. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29535. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29536. _this.size = size;
  29537. _this.side = side;
  29538. return _this;
  29539. }
  29540. Box.prototype._regenerateVertexData = function () {
  29541. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29542. };
  29543. Box.prototype.copy = function (id) {
  29544. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29545. };
  29546. Box.prototype.serialize = function () {
  29547. var serializationObject = _super.prototype.serialize.call(this);
  29548. serializationObject.size = this.size;
  29549. return serializationObject;
  29550. };
  29551. Box.Parse = function (parsedBox, scene) {
  29552. if (scene.getGeometryByID(parsedBox.id)) {
  29553. return null; // null since geometry could be something else than a box...
  29554. }
  29555. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29556. if (BABYLON.Tags) {
  29557. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  29558. }
  29559. scene.pushGeometry(box, true);
  29560. return box;
  29561. };
  29562. return Box;
  29563. }(_Primitive));
  29564. Primitives.Box = Box;
  29565. var Sphere = (function (_super) {
  29566. __extends(Sphere, _super);
  29567. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29568. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29569. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29570. _this.segments = segments;
  29571. _this.diameter = diameter;
  29572. _this.side = side;
  29573. return _this;
  29574. }
  29575. Sphere.prototype._regenerateVertexData = function () {
  29576. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29577. };
  29578. Sphere.prototype.copy = function (id) {
  29579. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29580. };
  29581. Sphere.prototype.serialize = function () {
  29582. var serializationObject = _super.prototype.serialize.call(this);
  29583. serializationObject.segments = this.segments;
  29584. serializationObject.diameter = this.diameter;
  29585. return serializationObject;
  29586. };
  29587. Sphere.Parse = function (parsedSphere, scene) {
  29588. if (scene.getGeometryByID(parsedSphere.id)) {
  29589. return null; // null since geometry could be something else than a sphere...
  29590. }
  29591. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29592. if (BABYLON.Tags) {
  29593. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29594. }
  29595. scene.pushGeometry(sphere, true);
  29596. return sphere;
  29597. };
  29598. return Sphere;
  29599. }(_Primitive));
  29600. Primitives.Sphere = Sphere;
  29601. var Disc = (function (_super) {
  29602. __extends(Disc, _super);
  29603. // Members
  29604. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29605. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29606. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29607. _this.radius = radius;
  29608. _this.tessellation = tessellation;
  29609. _this.side = side;
  29610. return _this;
  29611. }
  29612. Disc.prototype._regenerateVertexData = function () {
  29613. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29614. };
  29615. Disc.prototype.copy = function (id) {
  29616. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29617. };
  29618. return Disc;
  29619. }(_Primitive));
  29620. Primitives.Disc = Disc;
  29621. var Cylinder = (function (_super) {
  29622. __extends(Cylinder, _super);
  29623. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29624. if (subdivisions === void 0) { subdivisions = 1; }
  29625. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29626. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29627. _this.height = height;
  29628. _this.diameterTop = diameterTop;
  29629. _this.diameterBottom = diameterBottom;
  29630. _this.tessellation = tessellation;
  29631. _this.subdivisions = subdivisions;
  29632. _this.side = side;
  29633. return _this;
  29634. }
  29635. Cylinder.prototype._regenerateVertexData = function () {
  29636. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29637. };
  29638. Cylinder.prototype.copy = function (id) {
  29639. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29640. };
  29641. Cylinder.prototype.serialize = function () {
  29642. var serializationObject = _super.prototype.serialize.call(this);
  29643. serializationObject.height = this.height;
  29644. serializationObject.diameterTop = this.diameterTop;
  29645. serializationObject.diameterBottom = this.diameterBottom;
  29646. serializationObject.tessellation = this.tessellation;
  29647. return serializationObject;
  29648. };
  29649. Cylinder.Parse = function (parsedCylinder, scene) {
  29650. if (scene.getGeometryByID(parsedCylinder.id)) {
  29651. return null; // null since geometry could be something else than a cylinder...
  29652. }
  29653. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29654. if (BABYLON.Tags) {
  29655. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29656. }
  29657. scene.pushGeometry(cylinder, true);
  29658. return cylinder;
  29659. };
  29660. return Cylinder;
  29661. }(_Primitive));
  29662. Primitives.Cylinder = Cylinder;
  29663. var Torus = (function (_super) {
  29664. __extends(Torus, _super);
  29665. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29666. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29667. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29668. _this.diameter = diameter;
  29669. _this.thickness = thickness;
  29670. _this.tessellation = tessellation;
  29671. _this.side = side;
  29672. return _this;
  29673. }
  29674. Torus.prototype._regenerateVertexData = function () {
  29675. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29676. };
  29677. Torus.prototype.copy = function (id) {
  29678. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29679. };
  29680. Torus.prototype.serialize = function () {
  29681. var serializationObject = _super.prototype.serialize.call(this);
  29682. serializationObject.diameter = this.diameter;
  29683. serializationObject.thickness = this.thickness;
  29684. serializationObject.tessellation = this.tessellation;
  29685. return serializationObject;
  29686. };
  29687. Torus.Parse = function (parsedTorus, scene) {
  29688. if (scene.getGeometryByID(parsedTorus.id)) {
  29689. return null; // null since geometry could be something else than a torus...
  29690. }
  29691. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29692. if (BABYLON.Tags) {
  29693. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29694. }
  29695. scene.pushGeometry(torus, true);
  29696. return torus;
  29697. };
  29698. return Torus;
  29699. }(_Primitive));
  29700. Primitives.Torus = Torus;
  29701. var Ground = (function (_super) {
  29702. __extends(Ground, _super);
  29703. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29704. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29705. _this.width = width;
  29706. _this.height = height;
  29707. _this.subdivisions = subdivisions;
  29708. return _this;
  29709. }
  29710. Ground.prototype._regenerateVertexData = function () {
  29711. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29712. };
  29713. Ground.prototype.copy = function (id) {
  29714. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29715. };
  29716. Ground.prototype.serialize = function () {
  29717. var serializationObject = _super.prototype.serialize.call(this);
  29718. serializationObject.width = this.width;
  29719. serializationObject.height = this.height;
  29720. serializationObject.subdivisions = this.subdivisions;
  29721. return serializationObject;
  29722. };
  29723. Ground.Parse = function (parsedGround, scene) {
  29724. if (scene.getGeometryByID(parsedGround.id)) {
  29725. return null; // null since geometry could be something else than a ground...
  29726. }
  29727. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29728. if (BABYLON.Tags) {
  29729. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29730. }
  29731. scene.pushGeometry(ground, true);
  29732. return ground;
  29733. };
  29734. return Ground;
  29735. }(_Primitive));
  29736. Primitives.Ground = Ground;
  29737. var TiledGround = (function (_super) {
  29738. __extends(TiledGround, _super);
  29739. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29740. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29741. _this.xmin = xmin;
  29742. _this.zmin = zmin;
  29743. _this.xmax = xmax;
  29744. _this.zmax = zmax;
  29745. _this.subdivisions = subdivisions;
  29746. _this.precision = precision;
  29747. return _this;
  29748. }
  29749. TiledGround.prototype._regenerateVertexData = function () {
  29750. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29751. };
  29752. TiledGround.prototype.copy = function (id) {
  29753. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29754. };
  29755. return TiledGround;
  29756. }(_Primitive));
  29757. Primitives.TiledGround = TiledGround;
  29758. var Plane = (function (_super) {
  29759. __extends(Plane, _super);
  29760. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29761. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29762. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29763. _this.size = size;
  29764. _this.side = side;
  29765. return _this;
  29766. }
  29767. Plane.prototype._regenerateVertexData = function () {
  29768. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29769. };
  29770. Plane.prototype.copy = function (id) {
  29771. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29772. };
  29773. Plane.prototype.serialize = function () {
  29774. var serializationObject = _super.prototype.serialize.call(this);
  29775. serializationObject.size = this.size;
  29776. return serializationObject;
  29777. };
  29778. Plane.Parse = function (parsedPlane, scene) {
  29779. if (scene.getGeometryByID(parsedPlane.id)) {
  29780. return null; // null since geometry could be something else than a ground...
  29781. }
  29782. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  29783. if (BABYLON.Tags) {
  29784. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  29785. }
  29786. scene.pushGeometry(plane, true);
  29787. return plane;
  29788. };
  29789. return Plane;
  29790. }(_Primitive));
  29791. Primitives.Plane = Plane;
  29792. var TorusKnot = (function (_super) {
  29793. __extends(TorusKnot, _super);
  29794. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29795. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29796. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29797. _this.radius = radius;
  29798. _this.tube = tube;
  29799. _this.radialSegments = radialSegments;
  29800. _this.tubularSegments = tubularSegments;
  29801. _this.p = p;
  29802. _this.q = q;
  29803. _this.side = side;
  29804. return _this;
  29805. }
  29806. TorusKnot.prototype._regenerateVertexData = function () {
  29807. 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 });
  29808. };
  29809. TorusKnot.prototype.copy = function (id) {
  29810. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29811. };
  29812. TorusKnot.prototype.serialize = function () {
  29813. var serializationObject = _super.prototype.serialize.call(this);
  29814. serializationObject.radius = this.radius;
  29815. serializationObject.tube = this.tube;
  29816. serializationObject.radialSegments = this.radialSegments;
  29817. serializationObject.tubularSegments = this.tubularSegments;
  29818. serializationObject.p = this.p;
  29819. serializationObject.q = this.q;
  29820. return serializationObject;
  29821. };
  29822. ;
  29823. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  29824. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  29825. return null; // null since geometry could be something else than a ground...
  29826. }
  29827. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  29828. if (BABYLON.Tags) {
  29829. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  29830. }
  29831. scene.pushGeometry(torusKnot, true);
  29832. return torusKnot;
  29833. };
  29834. return TorusKnot;
  29835. }(_Primitive));
  29836. Primitives.TorusKnot = TorusKnot;
  29837. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29838. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29839. })(BABYLON || (BABYLON = {}));
  29840. //# sourceMappingURL=babylon.geometry.js.map
  29841. var BABYLON;
  29842. (function (BABYLON) {
  29843. var PostProcessManager = (function () {
  29844. function PostProcessManager(scene) {
  29845. this._vertexBuffers = {};
  29846. this._scene = scene;
  29847. }
  29848. PostProcessManager.prototype._prepareBuffers = function () {
  29849. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29850. return;
  29851. }
  29852. // VBO
  29853. var vertices = [];
  29854. vertices.push(1, 1);
  29855. vertices.push(-1, 1);
  29856. vertices.push(-1, -1);
  29857. vertices.push(1, -1);
  29858. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29859. this._buildIndexBuffer();
  29860. };
  29861. PostProcessManager.prototype._buildIndexBuffer = function () {
  29862. // Indices
  29863. var indices = [];
  29864. indices.push(0);
  29865. indices.push(1);
  29866. indices.push(2);
  29867. indices.push(0);
  29868. indices.push(2);
  29869. indices.push(3);
  29870. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29871. };
  29872. PostProcessManager.prototype._rebuild = function () {
  29873. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29874. return;
  29875. }
  29876. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  29877. this._buildIndexBuffer();
  29878. };
  29879. // Methods
  29880. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  29881. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29882. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29883. return false;
  29884. }
  29885. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  29886. return true;
  29887. };
  29888. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  29889. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  29890. var engine = this._scene.getEngine();
  29891. for (var index = 0; index < postProcesses.length; index++) {
  29892. if (index < postProcesses.length - 1) {
  29893. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29894. }
  29895. else {
  29896. if (targetTexture) {
  29897. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  29898. }
  29899. else {
  29900. engine.restoreDefaultFramebuffer();
  29901. }
  29902. }
  29903. var pp = postProcesses[index];
  29904. var effect = pp.apply();
  29905. if (effect) {
  29906. pp.onBeforeRenderObservable.notifyObservers(effect);
  29907. // VBOs
  29908. this._prepareBuffers();
  29909. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29910. // Draw order
  29911. engine.draw(true, 0, 6);
  29912. pp.onAfterRenderObservable.notifyObservers(effect);
  29913. }
  29914. }
  29915. // Restore depth buffer
  29916. engine.setDepthBuffer(true);
  29917. engine.setDepthWrite(true);
  29918. };
  29919. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29920. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29921. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29922. return;
  29923. }
  29924. var engine = this._scene.getEngine();
  29925. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29926. if (index < len - 1) {
  29927. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29928. }
  29929. else {
  29930. if (targetTexture) {
  29931. engine.bindFramebuffer(targetTexture, faceIndex);
  29932. }
  29933. else {
  29934. engine.restoreDefaultFramebuffer();
  29935. }
  29936. }
  29937. if (doNotPresent) {
  29938. break;
  29939. }
  29940. var pp = postProcesses[index];
  29941. var effect = pp.apply();
  29942. if (effect) {
  29943. pp.onBeforeRenderObservable.notifyObservers(effect);
  29944. // VBOs
  29945. this._prepareBuffers();
  29946. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29947. // Draw order
  29948. engine.draw(true, 0, 6);
  29949. pp.onAfterRenderObservable.notifyObservers(effect);
  29950. }
  29951. }
  29952. // Restore states
  29953. engine.setDepthBuffer(true);
  29954. engine.setDepthWrite(true);
  29955. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29956. };
  29957. PostProcessManager.prototype.dispose = function () {
  29958. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29959. if (buffer) {
  29960. buffer.dispose();
  29961. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29962. }
  29963. if (this._indexBuffer) {
  29964. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29965. this._indexBuffer = null;
  29966. }
  29967. };
  29968. return PostProcessManager;
  29969. }());
  29970. BABYLON.PostProcessManager = PostProcessManager;
  29971. })(BABYLON || (BABYLON = {}));
  29972. //# sourceMappingURL=babylon.postProcessManager.js.map
  29973. var BABYLON;
  29974. (function (BABYLON) {
  29975. /**
  29976. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  29977. */
  29978. var PerformanceMonitor = (function () {
  29979. /**
  29980. * constructor
  29981. * @param frameSampleSize The number of samples required to saturate the sliding window
  29982. */
  29983. function PerformanceMonitor(frameSampleSize) {
  29984. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  29985. this._enabled = true;
  29986. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  29987. }
  29988. /**
  29989. * Samples current frame
  29990. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  29991. */
  29992. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  29993. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  29994. if (!this._enabled)
  29995. return;
  29996. if (this._lastFrameTimeMs != null) {
  29997. var dt = timeMs - this._lastFrameTimeMs;
  29998. this._rollingFrameTime.add(dt);
  29999. }
  30000. this._lastFrameTimeMs = timeMs;
  30001. };
  30002. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  30003. /**
  30004. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30005. * @return Average frame time in milliseconds
  30006. */
  30007. get: function () {
  30008. return this._rollingFrameTime.average;
  30009. },
  30010. enumerable: true,
  30011. configurable: true
  30012. });
  30013. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  30014. /**
  30015. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30016. * @return Frame time variance in milliseconds squared
  30017. */
  30018. get: function () {
  30019. return this._rollingFrameTime.variance;
  30020. },
  30021. enumerable: true,
  30022. configurable: true
  30023. });
  30024. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  30025. /**
  30026. * Returns the frame time of the most recent frame
  30027. * @return Frame time in milliseconds
  30028. */
  30029. get: function () {
  30030. return this._rollingFrameTime.history(0);
  30031. },
  30032. enumerable: true,
  30033. configurable: true
  30034. });
  30035. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  30036. /**
  30037. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  30038. * @return Framerate in frames per second
  30039. */
  30040. get: function () {
  30041. return 1000.0 / this._rollingFrameTime.average;
  30042. },
  30043. enumerable: true,
  30044. configurable: true
  30045. });
  30046. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  30047. /**
  30048. * Returns the average framerate in frames per second using the most recent frame time
  30049. * @return Framerate in frames per second
  30050. */
  30051. get: function () {
  30052. return 1000.0 / this._rollingFrameTime.history(0);
  30053. },
  30054. enumerable: true,
  30055. configurable: true
  30056. });
  30057. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  30058. /**
  30059. * Returns true if enough samples have been taken to completely fill the sliding window
  30060. * @return true if saturated
  30061. */
  30062. get: function () {
  30063. return this._rollingFrameTime.isSaturated();
  30064. },
  30065. enumerable: true,
  30066. configurable: true
  30067. });
  30068. /**
  30069. * Enables contributions to the sliding window sample set
  30070. */
  30071. PerformanceMonitor.prototype.enable = function () {
  30072. this._enabled = true;
  30073. };
  30074. /**
  30075. * Disables contributions to the sliding window sample set
  30076. * Samples will not be interpolated over the disabled period
  30077. */
  30078. PerformanceMonitor.prototype.disable = function () {
  30079. this._enabled = false;
  30080. //clear last sample to avoid interpolating over the disabled period when next enabled
  30081. this._lastFrameTimeMs = null;
  30082. this._lastChangeTimeMs = null;
  30083. };
  30084. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  30085. /**
  30086. * Returns true if sampling is enabled
  30087. * @return true if enabled
  30088. */
  30089. get: function () {
  30090. return this._enabled;
  30091. },
  30092. enumerable: true,
  30093. configurable: true
  30094. });
  30095. /**
  30096. * Resets performance monitor
  30097. */
  30098. PerformanceMonitor.prototype.reset = function () {
  30099. //clear last sample to avoid interpolating over the disabled period when next enabled
  30100. this._lastFrameTimeMs = null;
  30101. this._lastChangeTimeMs = null;
  30102. //wipe record
  30103. this._rollingFrameTime.reset();
  30104. };
  30105. return PerformanceMonitor;
  30106. }());
  30107. BABYLON.PerformanceMonitor = PerformanceMonitor;
  30108. /**
  30109. * RollingAverage
  30110. *
  30111. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  30112. */
  30113. var RollingAverage = (function () {
  30114. /**
  30115. * constructor
  30116. * @param length The number of samples required to saturate the sliding window
  30117. */
  30118. function RollingAverage(length) {
  30119. this._samples = new Array(length);
  30120. this.reset();
  30121. }
  30122. /**
  30123. * Adds a sample to the sample set
  30124. * @param v The sample value
  30125. */
  30126. RollingAverage.prototype.add = function (v) {
  30127. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  30128. var delta;
  30129. //we need to check if we've already wrapped round
  30130. if (this.isSaturated()) {
  30131. //remove bottom of stack from mean
  30132. var bottomValue = this._samples[this._pos];
  30133. delta = bottomValue - this.average;
  30134. this.average -= delta / (this._sampleCount - 1);
  30135. this._m2 -= delta * (bottomValue - this.average);
  30136. }
  30137. else {
  30138. this._sampleCount++;
  30139. }
  30140. //add new value to mean
  30141. delta = v - this.average;
  30142. this.average += delta / (this._sampleCount);
  30143. this._m2 += delta * (v - this.average);
  30144. //set the new variance
  30145. this.variance = this._m2 / (this._sampleCount - 1);
  30146. this._samples[this._pos] = v;
  30147. this._pos++;
  30148. this._pos %= this._samples.length; //positive wrap around
  30149. };
  30150. /**
  30151. * Returns previously added values or null if outside of history or outside the sliding window domain
  30152. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  30153. * @return Value previously recorded with add() or null if outside of range
  30154. */
  30155. RollingAverage.prototype.history = function (i) {
  30156. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  30157. return null;
  30158. }
  30159. var i0 = this._wrapPosition(this._pos - 1.0);
  30160. return this._samples[this._wrapPosition(i0 - i)];
  30161. };
  30162. /**
  30163. * Returns true if enough samples have been taken to completely fill the sliding window
  30164. * @return true if sample-set saturated
  30165. */
  30166. RollingAverage.prototype.isSaturated = function () {
  30167. return this._sampleCount >= this._samples.length;
  30168. };
  30169. /**
  30170. * Resets the rolling average (equivalent to 0 samples taken so far)
  30171. */
  30172. RollingAverage.prototype.reset = function () {
  30173. this.average = 0;
  30174. this.variance = 0;
  30175. this._sampleCount = 0;
  30176. this._pos = 0;
  30177. this._m2 = 0;
  30178. };
  30179. /**
  30180. * Wraps a value around the sample range boundaries
  30181. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30182. * @return Wrapped position in sample range
  30183. */
  30184. RollingAverage.prototype._wrapPosition = function (i) {
  30185. var max = this._samples.length;
  30186. return ((i % max) + max) % max;
  30187. };
  30188. return RollingAverage;
  30189. }());
  30190. BABYLON.RollingAverage = RollingAverage;
  30191. })(BABYLON || (BABYLON = {}));
  30192. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30193. var BABYLON;
  30194. (function (BABYLON) {
  30195. var AnimationRange = (function () {
  30196. function AnimationRange(name, from, to) {
  30197. this.name = name;
  30198. this.from = from;
  30199. this.to = to;
  30200. }
  30201. AnimationRange.prototype.clone = function () {
  30202. return new AnimationRange(this.name, this.from, this.to);
  30203. };
  30204. return AnimationRange;
  30205. }());
  30206. BABYLON.AnimationRange = AnimationRange;
  30207. /**
  30208. * Composed of a frame, and an action function
  30209. */
  30210. var AnimationEvent = (function () {
  30211. function AnimationEvent(frame, action, onlyOnce) {
  30212. this.frame = frame;
  30213. this.action = action;
  30214. this.onlyOnce = onlyOnce;
  30215. this.isDone = false;
  30216. }
  30217. return AnimationEvent;
  30218. }());
  30219. BABYLON.AnimationEvent = AnimationEvent;
  30220. var PathCursor = (function () {
  30221. function PathCursor(path) {
  30222. this.path = path;
  30223. this._onchange = new Array();
  30224. this.value = 0;
  30225. this.animations = new Array();
  30226. }
  30227. PathCursor.prototype.getPoint = function () {
  30228. var point = this.path.getPointAtLengthPosition(this.value);
  30229. return new BABYLON.Vector3(point.x, 0, point.y);
  30230. };
  30231. PathCursor.prototype.moveAhead = function (step) {
  30232. if (step === void 0) { step = 0.002; }
  30233. this.move(step);
  30234. return this;
  30235. };
  30236. PathCursor.prototype.moveBack = function (step) {
  30237. if (step === void 0) { step = 0.002; }
  30238. this.move(-step);
  30239. return this;
  30240. };
  30241. PathCursor.prototype.move = function (step) {
  30242. if (Math.abs(step) > 1) {
  30243. throw "step size should be less than 1.";
  30244. }
  30245. this.value += step;
  30246. this.ensureLimits();
  30247. this.raiseOnChange();
  30248. return this;
  30249. };
  30250. PathCursor.prototype.ensureLimits = function () {
  30251. while (this.value > 1) {
  30252. this.value -= 1;
  30253. }
  30254. while (this.value < 0) {
  30255. this.value += 1;
  30256. }
  30257. return this;
  30258. };
  30259. // used by animation engine
  30260. PathCursor.prototype.markAsDirty = function (propertyName) {
  30261. this.ensureLimits();
  30262. this.raiseOnChange();
  30263. return this;
  30264. };
  30265. PathCursor.prototype.raiseOnChange = function () {
  30266. var _this = this;
  30267. this._onchange.forEach(function (f) { return f(_this); });
  30268. return this;
  30269. };
  30270. PathCursor.prototype.onchange = function (f) {
  30271. this._onchange.push(f);
  30272. return this;
  30273. };
  30274. return PathCursor;
  30275. }());
  30276. BABYLON.PathCursor = PathCursor;
  30277. var Animation = (function () {
  30278. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  30279. this.name = name;
  30280. this.targetProperty = targetProperty;
  30281. this.framePerSecond = framePerSecond;
  30282. this.dataType = dataType;
  30283. this.loopMode = loopMode;
  30284. this.enableBlending = enableBlending;
  30285. this._offsetsCache = {};
  30286. this._highLimitsCache = {};
  30287. this._stopped = false;
  30288. this._blendingFactor = 0;
  30289. // The set of event that will be linked to this animation
  30290. this._events = new Array();
  30291. this.allowMatricesInterpolation = false;
  30292. this.blendingSpeed = 0.01;
  30293. this._ranges = {};
  30294. this.targetPropertyPath = targetProperty.split(".");
  30295. this.dataType = dataType;
  30296. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  30297. }
  30298. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  30299. var dataType = undefined;
  30300. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  30301. dataType = Animation.ANIMATIONTYPE_FLOAT;
  30302. }
  30303. else if (from instanceof BABYLON.Quaternion) {
  30304. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  30305. }
  30306. else if (from instanceof BABYLON.Vector3) {
  30307. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  30308. }
  30309. else if (from instanceof BABYLON.Vector2) {
  30310. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  30311. }
  30312. else if (from instanceof BABYLON.Color3) {
  30313. dataType = Animation.ANIMATIONTYPE_COLOR3;
  30314. }
  30315. else if (from instanceof BABYLON.Size) {
  30316. dataType = Animation.ANIMATIONTYPE_SIZE;
  30317. }
  30318. if (dataType == undefined) {
  30319. return null;
  30320. }
  30321. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  30322. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  30323. animation.setKeys(keys);
  30324. if (easingFunction !== undefined) {
  30325. animation.setEasingFunction(easingFunction);
  30326. }
  30327. return animation;
  30328. };
  30329. /**
  30330. * Sets up an animation.
  30331. * @param property the property to animate
  30332. * @param animationType the animation type to apply
  30333. * @param easingFunction the easing function used in the animation
  30334. * @returns The created animation
  30335. */
  30336. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  30337. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  30338. animation.setEasingFunction(easingFunction);
  30339. return animation;
  30340. };
  30341. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30342. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30343. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30344. };
  30345. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30346. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30347. node.animations.push(animation);
  30348. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30349. };
  30350. /**
  30351. * Transition property of the Camera to the target Value.
  30352. * @param property The property to transition
  30353. * @param targetValue The target Value of the property
  30354. * @param host The object where the property to animate belongs
  30355. * @param scene Scene used to run the animation
  30356. * @param frameRate Framerate (in frame/s) to use
  30357. * @param transition The transition type we want to use
  30358. * @param duration The duration of the animation, in milliseconds
  30359. * @param onAnimationEnd Call back trigger at the end of the animation.
  30360. */
  30361. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  30362. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  30363. if (duration <= 0) {
  30364. host[property] = targetValue;
  30365. if (onAnimationEnd) {
  30366. onAnimationEnd();
  30367. }
  30368. return;
  30369. }
  30370. var endFrame = frameRate * (duration / 1000);
  30371. transition.setKeys([{
  30372. frame: 0,
  30373. value: host[property].clone ? host[property].clone() : host[property]
  30374. },
  30375. {
  30376. frame: endFrame,
  30377. value: targetValue
  30378. }]);
  30379. if (!host.animations) {
  30380. host.animations = [];
  30381. }
  30382. host.animations.push(transition);
  30383. var animation = scene.beginAnimation(host, 0, endFrame, false);
  30384. animation.onAnimationEnd = onAnimationEnd;
  30385. return animation;
  30386. };
  30387. // Methods
  30388. /**
  30389. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30390. */
  30391. Animation.prototype.toString = function (fullDetails) {
  30392. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  30393. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  30394. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  30395. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  30396. if (fullDetails) {
  30397. ret += ", Ranges: {";
  30398. var first = true;
  30399. for (var name in this._ranges) {
  30400. if (first) {
  30401. ret += ", ";
  30402. first = false;
  30403. }
  30404. ret += name;
  30405. }
  30406. ret += "}";
  30407. }
  30408. return ret;
  30409. };
  30410. /**
  30411. * Add an event to this animation.
  30412. */
  30413. Animation.prototype.addEvent = function (event) {
  30414. this._events.push(event);
  30415. };
  30416. /**
  30417. * Remove all events found at the given frame
  30418. * @param frame
  30419. */
  30420. Animation.prototype.removeEvents = function (frame) {
  30421. for (var index = 0; index < this._events.length; index++) {
  30422. if (this._events[index].frame === frame) {
  30423. this._events.splice(index, 1);
  30424. index--;
  30425. }
  30426. }
  30427. };
  30428. Animation.prototype.createRange = function (name, from, to) {
  30429. // check name not already in use; could happen for bones after serialized
  30430. if (!this._ranges[name]) {
  30431. this._ranges[name] = new AnimationRange(name, from, to);
  30432. }
  30433. };
  30434. Animation.prototype.deleteRange = function (name, deleteFrames) {
  30435. if (deleteFrames === void 0) { deleteFrames = true; }
  30436. if (this._ranges[name]) {
  30437. if (deleteFrames) {
  30438. var from = this._ranges[name].from;
  30439. var to = this._ranges[name].to;
  30440. // this loop MUST go high to low for multiple splices to work
  30441. for (var key = this._keys.length - 1; key >= 0; key--) {
  30442. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  30443. this._keys.splice(key, 1);
  30444. }
  30445. }
  30446. }
  30447. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  30448. }
  30449. };
  30450. Animation.prototype.getRange = function (name) {
  30451. return this._ranges[name];
  30452. };
  30453. Animation.prototype.reset = function () {
  30454. this._offsetsCache = {};
  30455. this._highLimitsCache = {};
  30456. this.currentFrame = 0;
  30457. this._blendingFactor = 0;
  30458. this._originalBlendValue = null;
  30459. };
  30460. Animation.prototype.isStopped = function () {
  30461. return this._stopped;
  30462. };
  30463. Animation.prototype.getKeys = function () {
  30464. return this._keys;
  30465. };
  30466. Animation.prototype.getHighestFrame = function () {
  30467. var ret = 0;
  30468. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  30469. if (ret < this._keys[key].frame) {
  30470. ret = this._keys[key].frame;
  30471. }
  30472. }
  30473. return ret;
  30474. };
  30475. Animation.prototype.getEasingFunction = function () {
  30476. return this._easingFunction;
  30477. };
  30478. Animation.prototype.setEasingFunction = function (easingFunction) {
  30479. this._easingFunction = easingFunction;
  30480. };
  30481. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  30482. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  30483. };
  30484. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30485. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30486. };
  30487. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  30488. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  30489. };
  30490. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30491. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  30492. };
  30493. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  30494. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  30495. };
  30496. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30497. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30498. };
  30499. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  30500. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  30501. };
  30502. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30503. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30504. };
  30505. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  30506. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  30507. };
  30508. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  30509. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  30510. };
  30511. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  30512. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  30513. };
  30514. Animation.prototype.clone = function () {
  30515. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  30516. clone.enableBlending = this.enableBlending;
  30517. clone.blendingSpeed = this.blendingSpeed;
  30518. if (this._keys) {
  30519. clone.setKeys(this._keys);
  30520. }
  30521. if (this._ranges) {
  30522. clone._ranges = {};
  30523. for (var name in this._ranges) {
  30524. clone._ranges[name] = this._ranges[name].clone();
  30525. }
  30526. }
  30527. return clone;
  30528. };
  30529. Animation.prototype.setKeys = function (values) {
  30530. this._keys = values.slice(0);
  30531. this._offsetsCache = {};
  30532. this._highLimitsCache = {};
  30533. };
  30534. Animation.prototype._getKeyValue = function (value) {
  30535. if (typeof value === "function") {
  30536. return value();
  30537. }
  30538. return value;
  30539. };
  30540. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  30541. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  30542. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  30543. }
  30544. this.currentFrame = currentFrame;
  30545. // Try to get a hash to find the right key
  30546. 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));
  30547. if (this._keys[startKeyIndex].frame >= currentFrame) {
  30548. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  30549. startKeyIndex--;
  30550. }
  30551. }
  30552. for (var key = startKeyIndex; key < this._keys.length; key++) {
  30553. var endKey = this._keys[key + 1];
  30554. if (endKey.frame >= currentFrame) {
  30555. var startKey = this._keys[key];
  30556. var startValue = this._getKeyValue(startKey.value);
  30557. var endValue = this._getKeyValue(endKey.value);
  30558. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  30559. var frameDelta = endKey.frame - startKey.frame;
  30560. // gradient : percent of currentFrame between the frame inf and the frame sup
  30561. var gradient = (currentFrame - startKey.frame) / frameDelta;
  30562. // check for easingFunction and correction of gradient
  30563. if (this._easingFunction != null) {
  30564. gradient = this._easingFunction.ease(gradient);
  30565. }
  30566. switch (this.dataType) {
  30567. // Float
  30568. case Animation.ANIMATIONTYPE_FLOAT:
  30569. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  30570. switch (loopMode) {
  30571. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30572. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30573. return floatValue;
  30574. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30575. return offsetValue * repeatCount + floatValue;
  30576. }
  30577. break;
  30578. // Quaternion
  30579. case Animation.ANIMATIONTYPE_QUATERNION:
  30580. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  30581. switch (loopMode) {
  30582. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30583. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30584. return quatValue;
  30585. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30586. return quatValue.add(offsetValue.scale(repeatCount));
  30587. }
  30588. return quatValue;
  30589. // Vector3
  30590. case Animation.ANIMATIONTYPE_VECTOR3:
  30591. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  30592. switch (loopMode) {
  30593. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30594. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30595. return vec3Value;
  30596. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30597. return vec3Value.add(offsetValue.scale(repeatCount));
  30598. }
  30599. // Vector2
  30600. case Animation.ANIMATIONTYPE_VECTOR2:
  30601. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  30602. switch (loopMode) {
  30603. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30604. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30605. return vec2Value;
  30606. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30607. return vec2Value.add(offsetValue.scale(repeatCount));
  30608. }
  30609. // Size
  30610. case Animation.ANIMATIONTYPE_SIZE:
  30611. switch (loopMode) {
  30612. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30613. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30614. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30615. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30616. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30617. }
  30618. // Color3
  30619. case Animation.ANIMATIONTYPE_COLOR3:
  30620. switch (loopMode) {
  30621. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30622. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30623. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30624. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30625. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30626. }
  30627. // Matrix
  30628. case Animation.ANIMATIONTYPE_MATRIX:
  30629. switch (loopMode) {
  30630. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30631. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30632. if (this.allowMatricesInterpolation) {
  30633. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30634. }
  30635. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30636. return startValue;
  30637. }
  30638. default:
  30639. break;
  30640. }
  30641. break;
  30642. }
  30643. }
  30644. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30645. };
  30646. Animation.prototype.setValue = function (currentValue, blend) {
  30647. if (blend === void 0) { blend = false; }
  30648. // Set value
  30649. var path;
  30650. var destination;
  30651. if (this.targetPropertyPath.length > 1) {
  30652. var property = this._target[this.targetPropertyPath[0]];
  30653. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30654. property = property[this.targetPropertyPath[index]];
  30655. }
  30656. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30657. destination = property;
  30658. }
  30659. else {
  30660. path = this.targetPropertyPath[0];
  30661. destination = this._target;
  30662. }
  30663. // Blending
  30664. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30665. if (!this._originalBlendValue) {
  30666. if (destination[path].clone) {
  30667. this._originalBlendValue = destination[path].clone();
  30668. }
  30669. else {
  30670. this._originalBlendValue = destination[path];
  30671. }
  30672. }
  30673. if (this._originalBlendValue.prototype) {
  30674. if (this._originalBlendValue.prototype.Lerp) {
  30675. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30676. }
  30677. else {
  30678. destination[path] = currentValue;
  30679. }
  30680. }
  30681. else if (this._originalBlendValue.m) {
  30682. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30683. }
  30684. else {
  30685. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30686. }
  30687. this._blendingFactor += this.blendingSpeed;
  30688. }
  30689. else {
  30690. destination[path] = currentValue;
  30691. }
  30692. if (this._target.markAsDirty) {
  30693. this._target.markAsDirty(this.targetProperty);
  30694. }
  30695. };
  30696. Animation.prototype.goToFrame = function (frame) {
  30697. if (frame < this._keys[0].frame) {
  30698. frame = this._keys[0].frame;
  30699. }
  30700. else if (frame > this._keys[this._keys.length - 1].frame) {
  30701. frame = this._keys[this._keys.length - 1].frame;
  30702. }
  30703. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30704. this.setValue(currentValue);
  30705. };
  30706. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30707. if (blend === void 0) { blend = false; }
  30708. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30709. this._stopped = true;
  30710. return false;
  30711. }
  30712. var returnValue = true;
  30713. // Adding a start key at frame 0 if missing
  30714. if (this._keys[0].frame !== 0) {
  30715. var newKey = { frame: 0, value: this._keys[0].value };
  30716. this._keys.splice(0, 0, newKey);
  30717. }
  30718. // Check limits
  30719. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30720. from = this._keys[0].frame;
  30721. }
  30722. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30723. to = this._keys[this._keys.length - 1].frame;
  30724. }
  30725. //to and from cannot be the same key
  30726. if (from === to) {
  30727. from++;
  30728. }
  30729. // Compute ratio
  30730. var range = to - from;
  30731. var offsetValue;
  30732. // ratio represents the frame delta between from and to
  30733. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30734. var highLimitValue = 0;
  30735. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  30736. returnValue = false;
  30737. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30738. }
  30739. else {
  30740. // Get max value if required
  30741. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30742. var keyOffset = to.toString() + from.toString();
  30743. if (!this._offsetsCache[keyOffset]) {
  30744. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30745. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30746. switch (this.dataType) {
  30747. // Float
  30748. case Animation.ANIMATIONTYPE_FLOAT:
  30749. this._offsetsCache[keyOffset] = toValue - fromValue;
  30750. break;
  30751. // Quaternion
  30752. case Animation.ANIMATIONTYPE_QUATERNION:
  30753. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30754. break;
  30755. // Vector3
  30756. case Animation.ANIMATIONTYPE_VECTOR3:
  30757. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30758. // Vector2
  30759. case Animation.ANIMATIONTYPE_VECTOR2:
  30760. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30761. // Size
  30762. case Animation.ANIMATIONTYPE_SIZE:
  30763. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30764. // Color3
  30765. case Animation.ANIMATIONTYPE_COLOR3:
  30766. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30767. default:
  30768. break;
  30769. }
  30770. this._highLimitsCache[keyOffset] = toValue;
  30771. }
  30772. highLimitValue = this._highLimitsCache[keyOffset];
  30773. offsetValue = this._offsetsCache[keyOffset];
  30774. }
  30775. }
  30776. if (offsetValue === undefined) {
  30777. switch (this.dataType) {
  30778. // Float
  30779. case Animation.ANIMATIONTYPE_FLOAT:
  30780. offsetValue = 0;
  30781. break;
  30782. // Quaternion
  30783. case Animation.ANIMATIONTYPE_QUATERNION:
  30784. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30785. break;
  30786. // Vector3
  30787. case Animation.ANIMATIONTYPE_VECTOR3:
  30788. offsetValue = BABYLON.Vector3.Zero();
  30789. break;
  30790. // Vector2
  30791. case Animation.ANIMATIONTYPE_VECTOR2:
  30792. offsetValue = BABYLON.Vector2.Zero();
  30793. break;
  30794. // Size
  30795. case Animation.ANIMATIONTYPE_SIZE:
  30796. offsetValue = BABYLON.Size.Zero();
  30797. break;
  30798. // Color3
  30799. case Animation.ANIMATIONTYPE_COLOR3:
  30800. offsetValue = BABYLON.Color3.Black();
  30801. }
  30802. }
  30803. // Compute value
  30804. var repeatCount = (ratio / range) >> 0;
  30805. var currentFrame = returnValue ? from + ratio % range : to;
  30806. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30807. // Set value
  30808. this.setValue(currentValue);
  30809. // Check events
  30810. for (var index = 0; index < this._events.length; index++) {
  30811. // Make sure current frame has passed event frame and that event frame is within the current range
  30812. // Also, handle both forward and reverse animations
  30813. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  30814. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  30815. var event = this._events[index];
  30816. if (!event.isDone) {
  30817. // If event should be done only once, remove it.
  30818. if (event.onlyOnce) {
  30819. this._events.splice(index, 1);
  30820. index--;
  30821. }
  30822. event.isDone = true;
  30823. event.action();
  30824. } // Don't do anything if the event has already be done.
  30825. }
  30826. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30827. // reset event, the animation is looping
  30828. this._events[index].isDone = false;
  30829. }
  30830. }
  30831. if (!returnValue) {
  30832. this._stopped = true;
  30833. }
  30834. return returnValue;
  30835. };
  30836. Animation.prototype.serialize = function () {
  30837. var serializationObject = {};
  30838. serializationObject.name = this.name;
  30839. serializationObject.property = this.targetProperty;
  30840. serializationObject.framePerSecond = this.framePerSecond;
  30841. serializationObject.dataType = this.dataType;
  30842. serializationObject.loopBehavior = this.loopMode;
  30843. serializationObject.enableBlending = this.enableBlending;
  30844. serializationObject.blendingSpeed = this.blendingSpeed;
  30845. var dataType = this.dataType;
  30846. serializationObject.keys = [];
  30847. var keys = this.getKeys();
  30848. for (var index = 0; index < keys.length; index++) {
  30849. var animationKey = keys[index];
  30850. var key = {};
  30851. key.frame = animationKey.frame;
  30852. switch (dataType) {
  30853. case Animation.ANIMATIONTYPE_FLOAT:
  30854. key.values = [animationKey.value];
  30855. break;
  30856. case Animation.ANIMATIONTYPE_QUATERNION:
  30857. case Animation.ANIMATIONTYPE_MATRIX:
  30858. case Animation.ANIMATIONTYPE_VECTOR3:
  30859. case Animation.ANIMATIONTYPE_COLOR3:
  30860. key.values = animationKey.value.asArray();
  30861. break;
  30862. }
  30863. serializationObject.keys.push(key);
  30864. }
  30865. serializationObject.ranges = [];
  30866. for (var name in this._ranges) {
  30867. var range = {};
  30868. range.name = name;
  30869. range.from = this._ranges[name].from;
  30870. range.to = this._ranges[name].to;
  30871. serializationObject.ranges.push(range);
  30872. }
  30873. return serializationObject;
  30874. };
  30875. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30876. get: function () {
  30877. return Animation._ANIMATIONTYPE_FLOAT;
  30878. },
  30879. enumerable: true,
  30880. configurable: true
  30881. });
  30882. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30883. get: function () {
  30884. return Animation._ANIMATIONTYPE_VECTOR3;
  30885. },
  30886. enumerable: true,
  30887. configurable: true
  30888. });
  30889. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30890. get: function () {
  30891. return Animation._ANIMATIONTYPE_VECTOR2;
  30892. },
  30893. enumerable: true,
  30894. configurable: true
  30895. });
  30896. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30897. get: function () {
  30898. return Animation._ANIMATIONTYPE_SIZE;
  30899. },
  30900. enumerable: true,
  30901. configurable: true
  30902. });
  30903. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30904. get: function () {
  30905. return Animation._ANIMATIONTYPE_QUATERNION;
  30906. },
  30907. enumerable: true,
  30908. configurable: true
  30909. });
  30910. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30911. get: function () {
  30912. return Animation._ANIMATIONTYPE_MATRIX;
  30913. },
  30914. enumerable: true,
  30915. configurable: true
  30916. });
  30917. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30918. get: function () {
  30919. return Animation._ANIMATIONTYPE_COLOR3;
  30920. },
  30921. enumerable: true,
  30922. configurable: true
  30923. });
  30924. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30925. get: function () {
  30926. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30927. },
  30928. enumerable: true,
  30929. configurable: true
  30930. });
  30931. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30932. get: function () {
  30933. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30934. },
  30935. enumerable: true,
  30936. configurable: true
  30937. });
  30938. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30939. get: function () {
  30940. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30941. },
  30942. enumerable: true,
  30943. configurable: true
  30944. });
  30945. Animation.Parse = function (parsedAnimation) {
  30946. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30947. var dataType = parsedAnimation.dataType;
  30948. var keys = [];
  30949. var data;
  30950. var index;
  30951. if (parsedAnimation.enableBlending) {
  30952. animation.enableBlending = parsedAnimation.enableBlending;
  30953. }
  30954. if (parsedAnimation.blendingSpeed) {
  30955. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30956. }
  30957. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30958. var key = parsedAnimation.keys[index];
  30959. switch (dataType) {
  30960. case Animation.ANIMATIONTYPE_FLOAT:
  30961. data = key.values[0];
  30962. break;
  30963. case Animation.ANIMATIONTYPE_QUATERNION:
  30964. data = BABYLON.Quaternion.FromArray(key.values);
  30965. break;
  30966. case Animation.ANIMATIONTYPE_MATRIX:
  30967. data = BABYLON.Matrix.FromArray(key.values);
  30968. break;
  30969. case Animation.ANIMATIONTYPE_COLOR3:
  30970. data = BABYLON.Color3.FromArray(key.values);
  30971. break;
  30972. case Animation.ANIMATIONTYPE_VECTOR3:
  30973. default:
  30974. data = BABYLON.Vector3.FromArray(key.values);
  30975. break;
  30976. }
  30977. keys.push({
  30978. frame: key.frame,
  30979. value: data
  30980. });
  30981. }
  30982. animation.setKeys(keys);
  30983. if (parsedAnimation.ranges) {
  30984. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30985. data = parsedAnimation.ranges[index];
  30986. animation.createRange(data.name, data.from, data.to);
  30987. }
  30988. }
  30989. return animation;
  30990. };
  30991. Animation.AppendSerializedAnimations = function (source, destination) {
  30992. if (source.animations) {
  30993. destination.animations = [];
  30994. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30995. var animation = source.animations[animationIndex];
  30996. destination.animations.push(animation.serialize());
  30997. }
  30998. }
  30999. };
  31000. // Statics
  31001. Animation._ANIMATIONTYPE_FLOAT = 0;
  31002. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  31003. Animation._ANIMATIONTYPE_QUATERNION = 2;
  31004. Animation._ANIMATIONTYPE_MATRIX = 3;
  31005. Animation._ANIMATIONTYPE_COLOR3 = 4;
  31006. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  31007. Animation._ANIMATIONTYPE_SIZE = 6;
  31008. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  31009. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  31010. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  31011. return Animation;
  31012. }());
  31013. BABYLON.Animation = Animation;
  31014. })(BABYLON || (BABYLON = {}));
  31015. //# sourceMappingURL=babylon.animation.js.map
  31016. var BABYLON;
  31017. (function (BABYLON) {
  31018. var Animatable = (function () {
  31019. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  31020. if (fromFrame === void 0) { fromFrame = 0; }
  31021. if (toFrame === void 0) { toFrame = 100; }
  31022. if (loopAnimation === void 0) { loopAnimation = false; }
  31023. if (speedRatio === void 0) { speedRatio = 1.0; }
  31024. this.target = target;
  31025. this.fromFrame = fromFrame;
  31026. this.toFrame = toFrame;
  31027. this.loopAnimation = loopAnimation;
  31028. this.speedRatio = speedRatio;
  31029. this.onAnimationEnd = onAnimationEnd;
  31030. this._localDelayOffset = null;
  31031. this._pausedDelay = null;
  31032. this._animations = new Array();
  31033. this._paused = false;
  31034. this.animationStarted = false;
  31035. if (animations) {
  31036. this.appendAnimations(target, animations);
  31037. }
  31038. this._scene = scene;
  31039. scene._activeAnimatables.push(this);
  31040. }
  31041. // Methods
  31042. Animatable.prototype.getAnimations = function () {
  31043. return this._animations;
  31044. };
  31045. Animatable.prototype.appendAnimations = function (target, animations) {
  31046. for (var index = 0; index < animations.length; index++) {
  31047. var animation = animations[index];
  31048. animation._target = target;
  31049. this._animations.push(animation);
  31050. }
  31051. };
  31052. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  31053. var animations = this._animations;
  31054. for (var index = 0; index < animations.length; index++) {
  31055. if (animations[index].targetProperty === property) {
  31056. return animations[index];
  31057. }
  31058. }
  31059. return null;
  31060. };
  31061. Animatable.prototype.reset = function () {
  31062. var animations = this._animations;
  31063. for (var index = 0; index < animations.length; index++) {
  31064. animations[index].reset();
  31065. }
  31066. this._localDelayOffset = null;
  31067. this._pausedDelay = null;
  31068. };
  31069. Animatable.prototype.enableBlending = function (blendingSpeed) {
  31070. var animations = this._animations;
  31071. for (var index = 0; index < animations.length; index++) {
  31072. animations[index].enableBlending = true;
  31073. animations[index].blendingSpeed = blendingSpeed;
  31074. }
  31075. };
  31076. Animatable.prototype.disableBlending = function () {
  31077. var animations = this._animations;
  31078. for (var index = 0; index < animations.length; index++) {
  31079. animations[index].enableBlending = false;
  31080. }
  31081. };
  31082. Animatable.prototype.goToFrame = function (frame) {
  31083. var animations = this._animations;
  31084. if (animations[0]) {
  31085. var fps = animations[0].framePerSecond;
  31086. var currentFrame = animations[0].currentFrame;
  31087. var adjustTime = frame - currentFrame;
  31088. var delay = adjustTime * 1000 / fps;
  31089. this._localDelayOffset -= delay;
  31090. }
  31091. for (var index = 0; index < animations.length; index++) {
  31092. animations[index].goToFrame(frame);
  31093. }
  31094. };
  31095. Animatable.prototype.pause = function () {
  31096. if (this._paused) {
  31097. return;
  31098. }
  31099. this._paused = true;
  31100. };
  31101. Animatable.prototype.restart = function () {
  31102. this._paused = false;
  31103. };
  31104. Animatable.prototype.stop = function (animationName) {
  31105. if (animationName) {
  31106. var idx = this._scene._activeAnimatables.indexOf(this);
  31107. if (idx > -1) {
  31108. var animations = this._animations;
  31109. for (var index = animations.length - 1; index >= 0; index--) {
  31110. if (typeof animationName === "string" && animations[index].name != animationName) {
  31111. continue;
  31112. }
  31113. animations[index].reset();
  31114. animations.splice(index, 1);
  31115. }
  31116. if (animations.length == 0) {
  31117. this._scene._activeAnimatables.splice(idx, 1);
  31118. if (this.onAnimationEnd) {
  31119. this.onAnimationEnd();
  31120. }
  31121. }
  31122. }
  31123. }
  31124. else {
  31125. var index = this._scene._activeAnimatables.indexOf(this);
  31126. if (index > -1) {
  31127. this._scene._activeAnimatables.splice(index, 1);
  31128. var animations = this._animations;
  31129. for (var index = 0; index < animations.length; index++) {
  31130. animations[index].reset();
  31131. }
  31132. if (this.onAnimationEnd) {
  31133. this.onAnimationEnd();
  31134. }
  31135. }
  31136. }
  31137. };
  31138. Animatable.prototype._animate = function (delay) {
  31139. if (this._paused) {
  31140. this.animationStarted = false;
  31141. if (this._pausedDelay === null) {
  31142. this._pausedDelay = delay;
  31143. }
  31144. return true;
  31145. }
  31146. if (this._localDelayOffset === null) {
  31147. this._localDelayOffset = delay;
  31148. }
  31149. else if (this._pausedDelay !== null) {
  31150. this._localDelayOffset += delay - this._pausedDelay;
  31151. this._pausedDelay = null;
  31152. }
  31153. // Animating
  31154. var running = false;
  31155. var animations = this._animations;
  31156. var index;
  31157. for (index = 0; index < animations.length; index++) {
  31158. var animation = animations[index];
  31159. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  31160. running = running || isRunning;
  31161. }
  31162. this.animationStarted = running;
  31163. if (!running) {
  31164. // Remove from active animatables
  31165. index = this._scene._activeAnimatables.indexOf(this);
  31166. this._scene._activeAnimatables.splice(index, 1);
  31167. }
  31168. if (!running && this.onAnimationEnd) {
  31169. this.onAnimationEnd();
  31170. this.onAnimationEnd = null;
  31171. }
  31172. return running;
  31173. };
  31174. return Animatable;
  31175. }());
  31176. BABYLON.Animatable = Animatable;
  31177. })(BABYLON || (BABYLON = {}));
  31178. //# sourceMappingURL=babylon.animatable.js.map
  31179. var BABYLON;
  31180. (function (BABYLON) {
  31181. var EasingFunction = (function () {
  31182. function EasingFunction() {
  31183. // Properties
  31184. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  31185. }
  31186. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  31187. get: function () {
  31188. return EasingFunction._EASINGMODE_EASEIN;
  31189. },
  31190. enumerable: true,
  31191. configurable: true
  31192. });
  31193. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  31194. get: function () {
  31195. return EasingFunction._EASINGMODE_EASEOUT;
  31196. },
  31197. enumerable: true,
  31198. configurable: true
  31199. });
  31200. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  31201. get: function () {
  31202. return EasingFunction._EASINGMODE_EASEINOUT;
  31203. },
  31204. enumerable: true,
  31205. configurable: true
  31206. });
  31207. EasingFunction.prototype.setEasingMode = function (easingMode) {
  31208. var n = Math.min(Math.max(easingMode, 0), 2);
  31209. this._easingMode = n;
  31210. };
  31211. EasingFunction.prototype.getEasingMode = function () {
  31212. return this._easingMode;
  31213. };
  31214. EasingFunction.prototype.easeInCore = function (gradient) {
  31215. throw new Error('You must implement this method');
  31216. };
  31217. EasingFunction.prototype.ease = function (gradient) {
  31218. switch (this._easingMode) {
  31219. case EasingFunction.EASINGMODE_EASEIN:
  31220. return this.easeInCore(gradient);
  31221. case EasingFunction.EASINGMODE_EASEOUT:
  31222. return (1 - this.easeInCore(1 - gradient));
  31223. }
  31224. if (gradient >= 0.5) {
  31225. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  31226. }
  31227. return (this.easeInCore(gradient * 2) * 0.5);
  31228. };
  31229. //Statics
  31230. EasingFunction._EASINGMODE_EASEIN = 0;
  31231. EasingFunction._EASINGMODE_EASEOUT = 1;
  31232. EasingFunction._EASINGMODE_EASEINOUT = 2;
  31233. return EasingFunction;
  31234. }());
  31235. BABYLON.EasingFunction = EasingFunction;
  31236. var CircleEase = (function (_super) {
  31237. __extends(CircleEase, _super);
  31238. function CircleEase() {
  31239. return _super !== null && _super.apply(this, arguments) || this;
  31240. }
  31241. CircleEase.prototype.easeInCore = function (gradient) {
  31242. gradient = Math.max(0, Math.min(1, gradient));
  31243. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  31244. };
  31245. return CircleEase;
  31246. }(EasingFunction));
  31247. BABYLON.CircleEase = CircleEase;
  31248. var BackEase = (function (_super) {
  31249. __extends(BackEase, _super);
  31250. function BackEase(amplitude) {
  31251. if (amplitude === void 0) { amplitude = 1; }
  31252. var _this = _super.call(this) || this;
  31253. _this.amplitude = amplitude;
  31254. return _this;
  31255. }
  31256. BackEase.prototype.easeInCore = function (gradient) {
  31257. var num = Math.max(0, this.amplitude);
  31258. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  31259. };
  31260. return BackEase;
  31261. }(EasingFunction));
  31262. BABYLON.BackEase = BackEase;
  31263. var BounceEase = (function (_super) {
  31264. __extends(BounceEase, _super);
  31265. function BounceEase(bounces, bounciness) {
  31266. if (bounces === void 0) { bounces = 3; }
  31267. if (bounciness === void 0) { bounciness = 2; }
  31268. var _this = _super.call(this) || this;
  31269. _this.bounces = bounces;
  31270. _this.bounciness = bounciness;
  31271. return _this;
  31272. }
  31273. BounceEase.prototype.easeInCore = function (gradient) {
  31274. var y = Math.max(0.0, this.bounces);
  31275. var bounciness = this.bounciness;
  31276. if (bounciness <= 1.0) {
  31277. bounciness = 1.001;
  31278. }
  31279. var num9 = Math.pow(bounciness, y);
  31280. var num5 = 1.0 - bounciness;
  31281. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  31282. var num15 = gradient * num4;
  31283. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  31284. var num3 = Math.floor(num65);
  31285. var num13 = num3 + 1.0;
  31286. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  31287. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  31288. var num7 = (num8 + num12) * 0.5;
  31289. var num6 = gradient - num7;
  31290. var num2 = num7 - num8;
  31291. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  31292. };
  31293. return BounceEase;
  31294. }(EasingFunction));
  31295. BABYLON.BounceEase = BounceEase;
  31296. var CubicEase = (function (_super) {
  31297. __extends(CubicEase, _super);
  31298. function CubicEase() {
  31299. return _super !== null && _super.apply(this, arguments) || this;
  31300. }
  31301. CubicEase.prototype.easeInCore = function (gradient) {
  31302. return (gradient * gradient * gradient);
  31303. };
  31304. return CubicEase;
  31305. }(EasingFunction));
  31306. BABYLON.CubicEase = CubicEase;
  31307. var ElasticEase = (function (_super) {
  31308. __extends(ElasticEase, _super);
  31309. function ElasticEase(oscillations, springiness) {
  31310. if (oscillations === void 0) { oscillations = 3; }
  31311. if (springiness === void 0) { springiness = 3; }
  31312. var _this = _super.call(this) || this;
  31313. _this.oscillations = oscillations;
  31314. _this.springiness = springiness;
  31315. return _this;
  31316. }
  31317. ElasticEase.prototype.easeInCore = function (gradient) {
  31318. var num2;
  31319. var num3 = Math.max(0.0, this.oscillations);
  31320. var num = Math.max(0.0, this.springiness);
  31321. if (num == 0) {
  31322. num2 = gradient;
  31323. }
  31324. else {
  31325. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  31326. }
  31327. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  31328. };
  31329. return ElasticEase;
  31330. }(EasingFunction));
  31331. BABYLON.ElasticEase = ElasticEase;
  31332. var ExponentialEase = (function (_super) {
  31333. __extends(ExponentialEase, _super);
  31334. function ExponentialEase(exponent) {
  31335. if (exponent === void 0) { exponent = 2; }
  31336. var _this = _super.call(this) || this;
  31337. _this.exponent = exponent;
  31338. return _this;
  31339. }
  31340. ExponentialEase.prototype.easeInCore = function (gradient) {
  31341. if (this.exponent <= 0) {
  31342. return gradient;
  31343. }
  31344. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  31345. };
  31346. return ExponentialEase;
  31347. }(EasingFunction));
  31348. BABYLON.ExponentialEase = ExponentialEase;
  31349. var PowerEase = (function (_super) {
  31350. __extends(PowerEase, _super);
  31351. function PowerEase(power) {
  31352. if (power === void 0) { power = 2; }
  31353. var _this = _super.call(this) || this;
  31354. _this.power = power;
  31355. return _this;
  31356. }
  31357. PowerEase.prototype.easeInCore = function (gradient) {
  31358. var y = Math.max(0.0, this.power);
  31359. return Math.pow(gradient, y);
  31360. };
  31361. return PowerEase;
  31362. }(EasingFunction));
  31363. BABYLON.PowerEase = PowerEase;
  31364. var QuadraticEase = (function (_super) {
  31365. __extends(QuadraticEase, _super);
  31366. function QuadraticEase() {
  31367. return _super !== null && _super.apply(this, arguments) || this;
  31368. }
  31369. QuadraticEase.prototype.easeInCore = function (gradient) {
  31370. return (gradient * gradient);
  31371. };
  31372. return QuadraticEase;
  31373. }(EasingFunction));
  31374. BABYLON.QuadraticEase = QuadraticEase;
  31375. var QuarticEase = (function (_super) {
  31376. __extends(QuarticEase, _super);
  31377. function QuarticEase() {
  31378. return _super !== null && _super.apply(this, arguments) || this;
  31379. }
  31380. QuarticEase.prototype.easeInCore = function (gradient) {
  31381. return (gradient * gradient * gradient * gradient);
  31382. };
  31383. return QuarticEase;
  31384. }(EasingFunction));
  31385. BABYLON.QuarticEase = QuarticEase;
  31386. var QuinticEase = (function (_super) {
  31387. __extends(QuinticEase, _super);
  31388. function QuinticEase() {
  31389. return _super !== null && _super.apply(this, arguments) || this;
  31390. }
  31391. QuinticEase.prototype.easeInCore = function (gradient) {
  31392. return (gradient * gradient * gradient * gradient * gradient);
  31393. };
  31394. return QuinticEase;
  31395. }(EasingFunction));
  31396. BABYLON.QuinticEase = QuinticEase;
  31397. var SineEase = (function (_super) {
  31398. __extends(SineEase, _super);
  31399. function SineEase() {
  31400. return _super !== null && _super.apply(this, arguments) || this;
  31401. }
  31402. SineEase.prototype.easeInCore = function (gradient) {
  31403. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  31404. };
  31405. return SineEase;
  31406. }(EasingFunction));
  31407. BABYLON.SineEase = SineEase;
  31408. var BezierCurveEase = (function (_super) {
  31409. __extends(BezierCurveEase, _super);
  31410. function BezierCurveEase(x1, y1, x2, y2) {
  31411. if (x1 === void 0) { x1 = 0; }
  31412. if (y1 === void 0) { y1 = 0; }
  31413. if (x2 === void 0) { x2 = 1; }
  31414. if (y2 === void 0) { y2 = 1; }
  31415. var _this = _super.call(this) || this;
  31416. _this.x1 = x1;
  31417. _this.y1 = y1;
  31418. _this.x2 = x2;
  31419. _this.y2 = y2;
  31420. return _this;
  31421. }
  31422. BezierCurveEase.prototype.easeInCore = function (gradient) {
  31423. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  31424. };
  31425. return BezierCurveEase;
  31426. }(EasingFunction));
  31427. BABYLON.BezierCurveEase = BezierCurveEase;
  31428. })(BABYLON || (BABYLON = {}));
  31429. //# sourceMappingURL=babylon.easing.js.map
  31430. var BABYLON;
  31431. (function (BABYLON) {
  31432. BABYLON.CameraInputTypes = {};
  31433. var CameraInputsManager = (function () {
  31434. function CameraInputsManager(camera) {
  31435. this.attached = {};
  31436. this.camera = camera;
  31437. this.checkInputs = function () { };
  31438. }
  31439. CameraInputsManager.prototype.add = function (input) {
  31440. var type = input.getSimpleName();
  31441. if (this.attached[type]) {
  31442. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  31443. return;
  31444. }
  31445. this.attached[type] = input;
  31446. input.camera = this.camera;
  31447. //for checkInputs, we are dynamically creating a function
  31448. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  31449. if (input.checkInputs) {
  31450. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31451. }
  31452. if (this.attachedElement) {
  31453. input.attachControl(this.attachedElement);
  31454. }
  31455. };
  31456. CameraInputsManager.prototype.remove = function (inputToRemove) {
  31457. for (var cam in this.attached) {
  31458. var input = this.attached[cam];
  31459. if (input === inputToRemove) {
  31460. input.detachControl(this.attachedElement);
  31461. input.camera = null;
  31462. delete this.attached[cam];
  31463. this.rebuildInputCheck();
  31464. }
  31465. }
  31466. };
  31467. CameraInputsManager.prototype.removeByType = function (inputType) {
  31468. for (var cam in this.attached) {
  31469. var input = this.attached[cam];
  31470. if (input.getClassName() === inputType) {
  31471. input.detachControl(this.attachedElement);
  31472. input.camera = null;
  31473. delete this.attached[cam];
  31474. this.rebuildInputCheck();
  31475. }
  31476. }
  31477. };
  31478. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  31479. var current = this.checkInputs;
  31480. return function () {
  31481. current();
  31482. fn();
  31483. };
  31484. };
  31485. CameraInputsManager.prototype.attachInput = function (input) {
  31486. input.attachControl(this.attachedElement, this.noPreventDefault);
  31487. };
  31488. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31489. if (this.attachedElement) {
  31490. return;
  31491. }
  31492. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31493. this.attachedElement = element;
  31494. this.noPreventDefault = noPreventDefault;
  31495. for (var cam in this.attached) {
  31496. var input = this.attached[cam];
  31497. this.attached[cam].attachControl(element, noPreventDefault);
  31498. }
  31499. };
  31500. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  31501. if (disconnect === void 0) { disconnect = false; }
  31502. if (this.attachedElement !== element) {
  31503. return;
  31504. }
  31505. for (var cam in this.attached) {
  31506. var input = this.attached[cam];
  31507. this.attached[cam].detachControl(element);
  31508. if (disconnect) {
  31509. this.attached[cam].camera = null;
  31510. }
  31511. }
  31512. this.attachedElement = null;
  31513. };
  31514. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31515. this.checkInputs = function () { };
  31516. for (var cam in this.attached) {
  31517. var input = this.attached[cam];
  31518. if (input.checkInputs) {
  31519. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31520. }
  31521. }
  31522. };
  31523. CameraInputsManager.prototype.clear = function () {
  31524. if (this.attachedElement) {
  31525. this.detachElement(this.attachedElement, true);
  31526. }
  31527. this.attached = {};
  31528. this.attachedElement = null;
  31529. this.checkInputs = function () { };
  31530. };
  31531. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31532. var inputs = {};
  31533. for (var cam in this.attached) {
  31534. var input = this.attached[cam];
  31535. var res = BABYLON.SerializationHelper.Serialize(input);
  31536. inputs[input.getClassName()] = res;
  31537. }
  31538. serializedCamera.inputsmgr = inputs;
  31539. };
  31540. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31541. var parsedInputs = parsedCamera.inputsmgr;
  31542. if (parsedInputs) {
  31543. this.clear();
  31544. for (var n in parsedInputs) {
  31545. var construct = BABYLON.CameraInputTypes[n];
  31546. if (construct) {
  31547. var parsedinput = parsedInputs[n];
  31548. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31549. this.add(input);
  31550. }
  31551. }
  31552. }
  31553. else {
  31554. //2016-03-08 this part is for managing backward compatibility
  31555. for (var n in this.attached) {
  31556. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  31557. if (construct) {
  31558. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31559. this.remove(this.attached[n]);
  31560. this.add(input);
  31561. }
  31562. }
  31563. }
  31564. };
  31565. return CameraInputsManager;
  31566. }());
  31567. BABYLON.CameraInputsManager = CameraInputsManager;
  31568. })(BABYLON || (BABYLON = {}));
  31569. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31570. /// <reference path="babylon.camera.ts" />
  31571. var BABYLON;
  31572. (function (BABYLON) {
  31573. var TargetCamera = (function (_super) {
  31574. __extends(TargetCamera, _super);
  31575. function TargetCamera(name, position, scene) {
  31576. var _this = _super.call(this, name, position, scene) || this;
  31577. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  31578. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  31579. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  31580. _this.speed = 2.0;
  31581. _this.noRotationConstraint = false;
  31582. _this.lockedTarget = null;
  31583. _this._currentTarget = BABYLON.Vector3.Zero();
  31584. _this._viewMatrix = BABYLON.Matrix.Zero();
  31585. _this._camMatrix = BABYLON.Matrix.Zero();
  31586. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  31587. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  31588. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  31589. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  31590. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  31591. _this._lookAtTemp = BABYLON.Matrix.Zero();
  31592. _this._tempMatrix = BABYLON.Matrix.Zero();
  31593. return _this;
  31594. }
  31595. TargetCamera.prototype.getFrontPosition = function (distance) {
  31596. var direction = this.getTarget().subtract(this.position);
  31597. direction.normalize();
  31598. direction.scaleInPlace(distance);
  31599. return this.globalPosition.add(direction);
  31600. };
  31601. TargetCamera.prototype._getLockedTargetPosition = function () {
  31602. if (!this.lockedTarget) {
  31603. return null;
  31604. }
  31605. if (this.lockedTarget.absolutePosition) {
  31606. this.lockedTarget.computeWorldMatrix();
  31607. }
  31608. return this.lockedTarget.absolutePosition || this.lockedTarget;
  31609. };
  31610. TargetCamera.prototype.storeState = function () {
  31611. this._storedPosition = this.position.clone();
  31612. this._storedRotation = this.rotation.clone();
  31613. if (this.rotationQuaternion) {
  31614. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  31615. }
  31616. return _super.prototype.storeState.call(this);
  31617. };
  31618. /**
  31619. * Restored camera state. You must call storeState() first
  31620. */
  31621. TargetCamera.prototype.restoreState = function () {
  31622. if (!_super.prototype.restoreState.call(this)) {
  31623. return false;
  31624. }
  31625. this.position = this._storedPosition.clone();
  31626. this.rotation = this._storedRotation.clone();
  31627. if (this.rotationQuaternion) {
  31628. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  31629. }
  31630. this.cameraDirection.copyFromFloats(0, 0, 0);
  31631. this.cameraRotation.copyFromFloats(0, 0);
  31632. return true;
  31633. };
  31634. // Cache
  31635. TargetCamera.prototype._initCache = function () {
  31636. _super.prototype._initCache.call(this);
  31637. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31638. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31639. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31640. };
  31641. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  31642. if (!ignoreParentClass) {
  31643. _super.prototype._updateCache.call(this);
  31644. }
  31645. var lockedTargetPosition = this._getLockedTargetPosition();
  31646. if (!lockedTargetPosition) {
  31647. this._cache.lockedTarget = null;
  31648. }
  31649. else {
  31650. if (!this._cache.lockedTarget) {
  31651. this._cache.lockedTarget = lockedTargetPosition.clone();
  31652. }
  31653. else {
  31654. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  31655. }
  31656. }
  31657. this._cache.rotation.copyFrom(this.rotation);
  31658. if (this.rotationQuaternion)
  31659. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31660. };
  31661. // Synchronized
  31662. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  31663. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  31664. return false;
  31665. }
  31666. var lockedTargetPosition = this._getLockedTargetPosition();
  31667. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  31668. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  31669. };
  31670. // Methods
  31671. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  31672. var engine = this.getEngine();
  31673. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  31674. };
  31675. // Target
  31676. TargetCamera.prototype.setTarget = function (target) {
  31677. this.upVector.normalize();
  31678. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  31679. this._camMatrix.invert();
  31680. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  31681. var vDir = target.subtract(this.position);
  31682. if (vDir.x >= 0.0) {
  31683. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  31684. }
  31685. else {
  31686. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  31687. }
  31688. this.rotation.z = 0;
  31689. if (isNaN(this.rotation.x)) {
  31690. this.rotation.x = 0;
  31691. }
  31692. if (isNaN(this.rotation.y)) {
  31693. this.rotation.y = 0;
  31694. }
  31695. if (isNaN(this.rotation.z)) {
  31696. this.rotation.z = 0;
  31697. }
  31698. if (this.rotationQuaternion) {
  31699. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31700. }
  31701. };
  31702. /**
  31703. * Return the current target position of the camera. This value is expressed in local space.
  31704. */
  31705. TargetCamera.prototype.getTarget = function () {
  31706. return this._currentTarget;
  31707. };
  31708. TargetCamera.prototype._decideIfNeedsToMove = function () {
  31709. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  31710. };
  31711. TargetCamera.prototype._updatePosition = function () {
  31712. if (this.parent) {
  31713. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  31714. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  31715. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  31716. return;
  31717. }
  31718. this.position.addInPlace(this.cameraDirection);
  31719. };
  31720. TargetCamera.prototype._checkInputs = function () {
  31721. var needToMove = this._decideIfNeedsToMove();
  31722. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  31723. // Move
  31724. if (needToMove) {
  31725. this._updatePosition();
  31726. }
  31727. // Rotate
  31728. if (needToRotate) {
  31729. this.rotation.x += this.cameraRotation.x;
  31730. this.rotation.y += this.cameraRotation.y;
  31731. //rotate, if quaternion is set and rotation was used
  31732. if (this.rotationQuaternion) {
  31733. var len = this.rotation.lengthSquared();
  31734. if (len) {
  31735. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31736. }
  31737. }
  31738. if (!this.noRotationConstraint) {
  31739. var limit = (Math.PI / 2) * 0.95;
  31740. if (this.rotation.x > limit)
  31741. this.rotation.x = limit;
  31742. if (this.rotation.x < -limit)
  31743. this.rotation.x = -limit;
  31744. }
  31745. }
  31746. // Inertia
  31747. if (needToMove) {
  31748. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  31749. this.cameraDirection.x = 0;
  31750. }
  31751. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  31752. this.cameraDirection.y = 0;
  31753. }
  31754. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  31755. this.cameraDirection.z = 0;
  31756. }
  31757. this.cameraDirection.scaleInPlace(this.inertia);
  31758. }
  31759. if (needToRotate) {
  31760. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  31761. this.cameraRotation.x = 0;
  31762. }
  31763. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  31764. this.cameraRotation.y = 0;
  31765. }
  31766. this.cameraRotation.scaleInPlace(this.inertia);
  31767. }
  31768. _super.prototype._checkInputs.call(this);
  31769. };
  31770. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  31771. if (this.rotationQuaternion) {
  31772. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  31773. //update the up vector!
  31774. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  31775. }
  31776. else {
  31777. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  31778. }
  31779. };
  31780. TargetCamera.prototype._getViewMatrix = function () {
  31781. if (!this.lockedTarget) {
  31782. // Compute
  31783. this._updateCameraRotationMatrix();
  31784. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  31785. // Computing target and final matrix
  31786. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  31787. }
  31788. else {
  31789. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  31790. }
  31791. if (this.getScene().useRightHandedSystem) {
  31792. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31793. }
  31794. else {
  31795. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31796. }
  31797. return this._viewMatrix;
  31798. };
  31799. /**
  31800. * @override
  31801. * Override Camera.createRigCamera
  31802. */
  31803. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31804. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  31805. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  31806. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  31807. if (!this.rotationQuaternion) {
  31808. this.rotationQuaternion = new BABYLON.Quaternion();
  31809. }
  31810. rigCamera._cameraRigParams = {};
  31811. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  31812. }
  31813. return rigCamera;
  31814. }
  31815. return null;
  31816. };
  31817. /**
  31818. * @override
  31819. * Override Camera._updateRigCameras
  31820. */
  31821. TargetCamera.prototype._updateRigCameras = function () {
  31822. var camLeft = this._rigCameras[0];
  31823. var camRight = this._rigCameras[1];
  31824. switch (this.cameraRigMode) {
  31825. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31826. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31827. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31828. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31829. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  31830. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  31831. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  31832. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  31833. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  31834. camLeft.setTarget(this.getTarget());
  31835. camRight.setTarget(this.getTarget());
  31836. break;
  31837. case BABYLON.Camera.RIG_MODE_VR:
  31838. if (camLeft.rotationQuaternion) {
  31839. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31840. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31841. }
  31842. else {
  31843. camLeft.rotation.copyFrom(this.rotation);
  31844. camRight.rotation.copyFrom(this.rotation);
  31845. }
  31846. camLeft.position.copyFrom(this.position);
  31847. camRight.position.copyFrom(this.position);
  31848. break;
  31849. }
  31850. _super.prototype._updateRigCameras.call(this);
  31851. };
  31852. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  31853. if (!this._rigCamTransformMatrix) {
  31854. this._rigCamTransformMatrix = new BABYLON.Matrix();
  31855. }
  31856. var target = this.getTarget();
  31857. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  31858. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  31859. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  31860. };
  31861. TargetCamera.prototype.getClassName = function () {
  31862. return "TargetCamera";
  31863. };
  31864. __decorate([
  31865. BABYLON.serializeAsVector3()
  31866. ], TargetCamera.prototype, "rotation", void 0);
  31867. __decorate([
  31868. BABYLON.serialize()
  31869. ], TargetCamera.prototype, "speed", void 0);
  31870. __decorate([
  31871. BABYLON.serializeAsMeshReference("lockedTargetId")
  31872. ], TargetCamera.prototype, "lockedTarget", void 0);
  31873. return TargetCamera;
  31874. }(BABYLON.Camera));
  31875. BABYLON.TargetCamera = TargetCamera;
  31876. })(BABYLON || (BABYLON = {}));
  31877. //# sourceMappingURL=babylon.targetCamera.js.map
  31878. var BABYLON;
  31879. (function (BABYLON) {
  31880. var ArcRotateCameraKeyboardMoveInput = (function () {
  31881. function ArcRotateCameraKeyboardMoveInput() {
  31882. this._keys = [];
  31883. this.keysUp = [38];
  31884. this.keysDown = [40];
  31885. this.keysLeft = [37];
  31886. this.keysRight = [39];
  31887. this.keysReset = [111];
  31888. this.panningSensibility = 50.0;
  31889. }
  31890. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  31891. var _this = this;
  31892. if (this._onCanvasBlurObserver) {
  31893. return;
  31894. }
  31895. this._scene = this.camera.getScene();
  31896. this._engine = this._scene.getEngine();
  31897. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  31898. _this._keys = [];
  31899. });
  31900. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  31901. var evt = info.event;
  31902. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  31903. _this._ctrlPressed = evt.ctrlKey;
  31904. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31905. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31906. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31907. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  31908. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  31909. var index = _this._keys.indexOf(evt.keyCode);
  31910. if (index === -1) {
  31911. _this._keys.push(evt.keyCode);
  31912. }
  31913. if (evt.preventDefault) {
  31914. if (!noPreventDefault) {
  31915. evt.preventDefault();
  31916. }
  31917. }
  31918. }
  31919. }
  31920. else {
  31921. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31922. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31923. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31924. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  31925. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  31926. var index = _this._keys.indexOf(evt.keyCode);
  31927. if (index >= 0) {
  31928. _this._keys.splice(index, 1);
  31929. }
  31930. if (evt.preventDefault) {
  31931. if (!noPreventDefault) {
  31932. evt.preventDefault();
  31933. }
  31934. }
  31935. }
  31936. }
  31937. });
  31938. };
  31939. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  31940. if (this._scene) {
  31941. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  31942. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  31943. this._onKeyboardObserver = null;
  31944. this._onCanvasBlurObserver = null;
  31945. }
  31946. this._keys = [];
  31947. };
  31948. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  31949. if (this._onKeyboardObserver) {
  31950. var camera = this.camera;
  31951. for (var index = 0; index < this._keys.length; index++) {
  31952. var keyCode = this._keys[index];
  31953. if (this.keysLeft.indexOf(keyCode) !== -1) {
  31954. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31955. camera.inertialPanningX -= 1 / this.panningSensibility;
  31956. }
  31957. else {
  31958. camera.inertialAlphaOffset -= 0.01;
  31959. }
  31960. }
  31961. else if (this.keysUp.indexOf(keyCode) !== -1) {
  31962. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31963. camera.inertialPanningY += 1 / this.panningSensibility;
  31964. }
  31965. else {
  31966. camera.inertialBetaOffset -= 0.01;
  31967. }
  31968. }
  31969. else if (this.keysRight.indexOf(keyCode) !== -1) {
  31970. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31971. camera.inertialPanningX += 1 / this.panningSensibility;
  31972. }
  31973. else {
  31974. camera.inertialAlphaOffset += 0.01;
  31975. }
  31976. }
  31977. else if (this.keysDown.indexOf(keyCode) !== -1) {
  31978. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  31979. camera.inertialPanningY -= 1 / this.panningSensibility;
  31980. }
  31981. else {
  31982. camera.inertialBetaOffset += 0.01;
  31983. }
  31984. }
  31985. else if (this.keysReset.indexOf(keyCode) !== -1) {
  31986. camera.restoreState();
  31987. }
  31988. }
  31989. }
  31990. };
  31991. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  31992. return "ArcRotateCameraKeyboardMoveInput";
  31993. };
  31994. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  31995. return "keyboard";
  31996. };
  31997. __decorate([
  31998. BABYLON.serialize()
  31999. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  32000. __decorate([
  32001. BABYLON.serialize()
  32002. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  32003. __decorate([
  32004. BABYLON.serialize()
  32005. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  32006. __decorate([
  32007. BABYLON.serialize()
  32008. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  32009. __decorate([
  32010. BABYLON.serialize()
  32011. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  32012. __decorate([
  32013. BABYLON.serialize()
  32014. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  32015. return ArcRotateCameraKeyboardMoveInput;
  32016. }());
  32017. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  32018. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  32019. })(BABYLON || (BABYLON = {}));
  32020. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  32021. var BABYLON;
  32022. (function (BABYLON) {
  32023. var ArcRotateCameraMouseWheelInput = (function () {
  32024. function ArcRotateCameraMouseWheelInput() {
  32025. this.wheelPrecision = 3.0;
  32026. }
  32027. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  32028. var _this = this;
  32029. this._wheel = function (p, s) {
  32030. //sanity check - this should be a PointerWheel event.
  32031. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  32032. return;
  32033. var event = p.event;
  32034. var delta = 0;
  32035. if (event.wheelDelta) {
  32036. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  32037. }
  32038. else if (event.detail) {
  32039. delta = -event.detail / _this.wheelPrecision;
  32040. }
  32041. if (delta)
  32042. _this.camera.inertialRadiusOffset += delta;
  32043. if (event.preventDefault) {
  32044. if (!noPreventDefault) {
  32045. event.preventDefault();
  32046. }
  32047. }
  32048. };
  32049. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  32050. };
  32051. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  32052. if (this._observer && element) {
  32053. this.camera.getScene().onPointerObservable.remove(this._observer);
  32054. this._observer = null;
  32055. this._wheel = null;
  32056. }
  32057. };
  32058. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  32059. return "ArcRotateCameraMouseWheelInput";
  32060. };
  32061. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  32062. return "mousewheel";
  32063. };
  32064. __decorate([
  32065. BABYLON.serialize()
  32066. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  32067. return ArcRotateCameraMouseWheelInput;
  32068. }());
  32069. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  32070. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  32071. })(BABYLON || (BABYLON = {}));
  32072. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  32073. var BABYLON;
  32074. (function (BABYLON) {
  32075. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  32076. var ArcRotateCameraPointersInput = (function () {
  32077. function ArcRotateCameraPointersInput() {
  32078. this.buttons = [0, 1, 2];
  32079. this.angularSensibilityX = 1000.0;
  32080. this.angularSensibilityY = 1000.0;
  32081. this.pinchPrecision = 6.0;
  32082. this.panningSensibility = 50.0;
  32083. this._isPanClick = false;
  32084. this.pinchInwards = true;
  32085. }
  32086. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  32087. var _this = this;
  32088. var engine = this.camera.getEngine();
  32089. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  32090. var pointA, pointB;
  32091. var previousPinchDistance = 0;
  32092. this._pointerInput = function (p, s) {
  32093. var evt = p.event;
  32094. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  32095. return;
  32096. }
  32097. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  32098. try {
  32099. evt.srcElement.setPointerCapture(evt.pointerId);
  32100. }
  32101. catch (e) {
  32102. //Nothing to do with the error. Execution will continue.
  32103. }
  32104. // Manage panning with pan button click
  32105. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  32106. // manage pointers
  32107. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  32108. if (pointA === undefined) {
  32109. pointA = cacheSoloPointer;
  32110. }
  32111. else if (pointB === undefined) {
  32112. pointB = cacheSoloPointer;
  32113. }
  32114. if (!noPreventDefault) {
  32115. evt.preventDefault();
  32116. element.focus();
  32117. }
  32118. }
  32119. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  32120. _this.camera.restoreState();
  32121. }
  32122. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  32123. try {
  32124. evt.srcElement.releasePointerCapture(evt.pointerId);
  32125. }
  32126. catch (e) {
  32127. //Nothing to do with the error.
  32128. }
  32129. cacheSoloPointer = null;
  32130. previousPinchDistance = 0;
  32131. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  32132. //but emptying completly pointers collection is required to fix a bug on iPhone :
  32133. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  32134. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  32135. pointA = pointB = undefined;
  32136. if (!noPreventDefault) {
  32137. evt.preventDefault();
  32138. }
  32139. }
  32140. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  32141. if (!noPreventDefault) {
  32142. evt.preventDefault();
  32143. }
  32144. // One button down
  32145. if (pointA && pointB === undefined) {
  32146. if (_this.panningSensibility !== 0 &&
  32147. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  32148. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  32149. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  32150. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  32151. }
  32152. else {
  32153. var offsetX = evt.clientX - cacheSoloPointer.x;
  32154. var offsetY = evt.clientY - cacheSoloPointer.y;
  32155. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32156. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32157. }
  32158. cacheSoloPointer.x = evt.clientX;
  32159. cacheSoloPointer.y = evt.clientY;
  32160. }
  32161. else if (pointA && pointB) {
  32162. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  32163. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  32164. ed.x = evt.clientX;
  32165. ed.y = evt.clientY;
  32166. var direction = _this.pinchInwards ? 1 : -1;
  32167. var distX = pointA.x - pointB.x;
  32168. var distY = pointA.y - pointB.y;
  32169. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  32170. if (previousPinchDistance === 0) {
  32171. previousPinchDistance = pinchSquaredDistance;
  32172. return;
  32173. }
  32174. if (pinchSquaredDistance !== previousPinchDistance) {
  32175. _this.camera
  32176. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  32177. (_this.pinchPrecision *
  32178. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  32179. direction);
  32180. previousPinchDistance = pinchSquaredDistance;
  32181. }
  32182. }
  32183. }
  32184. };
  32185. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  32186. this._onContextMenu = function (evt) {
  32187. evt.preventDefault();
  32188. };
  32189. if (!this.camera._useCtrlForPanning) {
  32190. element.addEventListener("contextmenu", this._onContextMenu, false);
  32191. }
  32192. this._onLostFocus = function () {
  32193. //this._keys = [];
  32194. pointA = pointB = undefined;
  32195. previousPinchDistance = 0;
  32196. cacheSoloPointer = null;
  32197. };
  32198. this._onMouseMove = function (evt) {
  32199. if (!engine.isPointerLock) {
  32200. return;
  32201. }
  32202. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  32203. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  32204. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32205. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32206. if (!noPreventDefault) {
  32207. evt.preventDefault();
  32208. }
  32209. };
  32210. this._onGestureStart = function (e) {
  32211. if (window.MSGesture === undefined) {
  32212. return;
  32213. }
  32214. if (!_this._MSGestureHandler) {
  32215. _this._MSGestureHandler = new MSGesture();
  32216. _this._MSGestureHandler.target = element;
  32217. }
  32218. _this._MSGestureHandler.addPointer(e.pointerId);
  32219. };
  32220. this._onGesture = function (e) {
  32221. _this.camera.radius *= e.scale;
  32222. if (e.preventDefault) {
  32223. if (!noPreventDefault) {
  32224. e.stopPropagation();
  32225. e.preventDefault();
  32226. }
  32227. }
  32228. };
  32229. element.addEventListener("mousemove", this._onMouseMove, false);
  32230. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  32231. element.addEventListener("MSGestureChange", this._onGesture, false);
  32232. BABYLON.Tools.RegisterTopRootEvents([
  32233. { name: "blur", handler: this._onLostFocus }
  32234. ]);
  32235. };
  32236. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  32237. BABYLON.Tools.UnregisterTopRootEvents([
  32238. { name: "blur", handler: this._onLostFocus }
  32239. ]);
  32240. if (element && this._observer) {
  32241. this.camera.getScene().onPointerObservable.remove(this._observer);
  32242. this._observer = null;
  32243. element.removeEventListener("contextmenu", this._onContextMenu);
  32244. element.removeEventListener("mousemove", this._onMouseMove);
  32245. element.removeEventListener("MSPointerDown", this._onGestureStart);
  32246. element.removeEventListener("MSGestureChange", this._onGesture);
  32247. this._isPanClick = false;
  32248. this.pinchInwards = true;
  32249. this._onMouseMove = null;
  32250. this._onGestureStart = null;
  32251. this._onGesture = null;
  32252. this._MSGestureHandler = null;
  32253. this._onLostFocus = null;
  32254. this._onContextMenu = null;
  32255. }
  32256. };
  32257. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  32258. return "ArcRotateCameraPointersInput";
  32259. };
  32260. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  32261. return "pointers";
  32262. };
  32263. __decorate([
  32264. BABYLON.serialize()
  32265. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  32266. __decorate([
  32267. BABYLON.serialize()
  32268. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  32269. __decorate([
  32270. BABYLON.serialize()
  32271. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  32272. __decorate([
  32273. BABYLON.serialize()
  32274. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  32275. __decorate([
  32276. BABYLON.serialize()
  32277. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  32278. return ArcRotateCameraPointersInput;
  32279. }());
  32280. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  32281. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  32282. })(BABYLON || (BABYLON = {}));
  32283. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  32284. /// <reference path="babylon.targetCamera.ts" />
  32285. /// <reference path="..\Tools\babylon.tools.ts" />
  32286. var BABYLON;
  32287. (function (BABYLON) {
  32288. var ArcRotateCamera = (function (_super) {
  32289. __extends(ArcRotateCamera, _super);
  32290. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  32291. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  32292. _this.inertialAlphaOffset = 0;
  32293. _this.inertialBetaOffset = 0;
  32294. _this.inertialRadiusOffset = 0;
  32295. _this.lowerAlphaLimit = null;
  32296. _this.upperAlphaLimit = null;
  32297. _this.lowerBetaLimit = 0.01;
  32298. _this.upperBetaLimit = Math.PI;
  32299. _this.lowerRadiusLimit = null;
  32300. _this.upperRadiusLimit = null;
  32301. _this.inertialPanningX = 0;
  32302. _this.inertialPanningY = 0;
  32303. _this.panningInertia = 0.9;
  32304. //-- end properties for backward compatibility for inputs
  32305. _this.zoomOnFactor = 1;
  32306. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  32307. _this.allowUpsideDown = true;
  32308. _this._viewMatrix = new BABYLON.Matrix();
  32309. // Panning
  32310. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  32311. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  32312. _this.checkCollisions = false;
  32313. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  32314. _this._previousPosition = BABYLON.Vector3.Zero();
  32315. _this._collisionVelocity = BABYLON.Vector3.Zero();
  32316. _this._newPosition = BABYLON.Vector3.Zero();
  32317. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32318. if (collidedMesh === void 0) { collidedMesh = null; }
  32319. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  32320. newPosition.multiplyInPlace(_this._collider.radius);
  32321. }
  32322. if (!collidedMesh) {
  32323. _this._previousPosition.copyFrom(_this.position);
  32324. }
  32325. else {
  32326. _this.setPosition(newPosition);
  32327. if (_this.onCollide) {
  32328. _this.onCollide(collidedMesh);
  32329. }
  32330. }
  32331. // Recompute because of constraints
  32332. var cosa = Math.cos(_this.alpha);
  32333. var sina = Math.sin(_this.alpha);
  32334. var cosb = Math.cos(_this.beta);
  32335. var sinb = Math.sin(_this.beta);
  32336. if (sinb === 0) {
  32337. sinb = 0.0001;
  32338. }
  32339. var target = _this._getTargetPosition();
  32340. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  32341. _this.position.copyFrom(_this._newPosition);
  32342. var up = _this.upVector;
  32343. if (_this.allowUpsideDown && _this.beta < 0) {
  32344. up = up.clone();
  32345. up = up.negate();
  32346. }
  32347. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  32348. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  32349. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  32350. _this._collisionTriggered = false;
  32351. };
  32352. _this._target = BABYLON.Vector3.Zero();
  32353. if (target) {
  32354. _this.setTarget(target);
  32355. }
  32356. _this.alpha = alpha;
  32357. _this.beta = beta;
  32358. _this.radius = radius;
  32359. _this.getViewMatrix();
  32360. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  32361. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  32362. return _this;
  32363. }
  32364. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  32365. get: function () {
  32366. return this._target;
  32367. },
  32368. set: function (value) {
  32369. this.setTarget(value);
  32370. },
  32371. enumerable: true,
  32372. configurable: true
  32373. });
  32374. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  32375. //-- begin properties for backward compatibility for inputs
  32376. get: function () {
  32377. var pointers = this.inputs.attached["pointers"];
  32378. if (pointers)
  32379. return pointers.angularSensibilityX;
  32380. },
  32381. set: function (value) {
  32382. var pointers = this.inputs.attached["pointers"];
  32383. if (pointers) {
  32384. pointers.angularSensibilityX = value;
  32385. }
  32386. },
  32387. enumerable: true,
  32388. configurable: true
  32389. });
  32390. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  32391. get: function () {
  32392. var pointers = this.inputs.attached["pointers"];
  32393. if (pointers)
  32394. return pointers.angularSensibilityY;
  32395. },
  32396. set: function (value) {
  32397. var pointers = this.inputs.attached["pointers"];
  32398. if (pointers) {
  32399. pointers.angularSensibilityY = value;
  32400. }
  32401. },
  32402. enumerable: true,
  32403. configurable: true
  32404. });
  32405. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  32406. get: function () {
  32407. var pointers = this.inputs.attached["pointers"];
  32408. if (pointers)
  32409. return pointers.pinchPrecision;
  32410. },
  32411. set: function (value) {
  32412. var pointers = this.inputs.attached["pointers"];
  32413. if (pointers) {
  32414. pointers.pinchPrecision = value;
  32415. }
  32416. },
  32417. enumerable: true,
  32418. configurable: true
  32419. });
  32420. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  32421. get: function () {
  32422. var pointers = this.inputs.attached["pointers"];
  32423. if (pointers)
  32424. return pointers.panningSensibility;
  32425. },
  32426. set: function (value) {
  32427. var pointers = this.inputs.attached["pointers"];
  32428. if (pointers) {
  32429. pointers.panningSensibility = value;
  32430. }
  32431. },
  32432. enumerable: true,
  32433. configurable: true
  32434. });
  32435. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  32436. get: function () {
  32437. var keyboard = this.inputs.attached["keyboard"];
  32438. if (keyboard)
  32439. return keyboard.keysUp;
  32440. },
  32441. set: function (value) {
  32442. var keyboard = this.inputs.attached["keyboard"];
  32443. if (keyboard)
  32444. keyboard.keysUp = value;
  32445. },
  32446. enumerable: true,
  32447. configurable: true
  32448. });
  32449. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  32450. get: function () {
  32451. var keyboard = this.inputs.attached["keyboard"];
  32452. if (keyboard)
  32453. return keyboard.keysDown;
  32454. },
  32455. set: function (value) {
  32456. var keyboard = this.inputs.attached["keyboard"];
  32457. if (keyboard)
  32458. keyboard.keysDown = value;
  32459. },
  32460. enumerable: true,
  32461. configurable: true
  32462. });
  32463. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  32464. get: function () {
  32465. var keyboard = this.inputs.attached["keyboard"];
  32466. if (keyboard)
  32467. return keyboard.keysLeft;
  32468. },
  32469. set: function (value) {
  32470. var keyboard = this.inputs.attached["keyboard"];
  32471. if (keyboard)
  32472. keyboard.keysLeft = value;
  32473. },
  32474. enumerable: true,
  32475. configurable: true
  32476. });
  32477. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  32478. get: function () {
  32479. var keyboard = this.inputs.attached["keyboard"];
  32480. if (keyboard)
  32481. return keyboard.keysRight;
  32482. },
  32483. set: function (value) {
  32484. var keyboard = this.inputs.attached["keyboard"];
  32485. if (keyboard)
  32486. keyboard.keysRight = value;
  32487. },
  32488. enumerable: true,
  32489. configurable: true
  32490. });
  32491. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  32492. get: function () {
  32493. var mousewheel = this.inputs.attached["mousewheel"];
  32494. if (mousewheel)
  32495. return mousewheel.wheelPrecision;
  32496. },
  32497. set: function (value) {
  32498. var mousewheel = this.inputs.attached["mousewheel"];
  32499. if (mousewheel)
  32500. mousewheel.wheelPrecision = value;
  32501. },
  32502. enumerable: true,
  32503. configurable: true
  32504. });
  32505. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  32506. get: function () {
  32507. return this._bouncingBehavior;
  32508. },
  32509. enumerable: true,
  32510. configurable: true
  32511. });
  32512. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  32513. get: function () {
  32514. return this._bouncingBehavior != null;
  32515. },
  32516. set: function (value) {
  32517. if (value === this.useBouncingBehavior) {
  32518. return;
  32519. }
  32520. if (value) {
  32521. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  32522. this.addBehavior(this._bouncingBehavior);
  32523. }
  32524. else {
  32525. this.removeBehavior(this._bouncingBehavior);
  32526. this._bouncingBehavior = null;
  32527. }
  32528. },
  32529. enumerable: true,
  32530. configurable: true
  32531. });
  32532. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  32533. get: function () {
  32534. return this._framingBehavior;
  32535. },
  32536. enumerable: true,
  32537. configurable: true
  32538. });
  32539. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  32540. get: function () {
  32541. return this._framingBehavior != null;
  32542. },
  32543. set: function (value) {
  32544. if (value === this.useFramingBehavior) {
  32545. return;
  32546. }
  32547. if (value) {
  32548. this._framingBehavior = new BABYLON.FramingBehavior();
  32549. this.addBehavior(this._framingBehavior);
  32550. }
  32551. else {
  32552. this.removeBehavior(this._framingBehavior);
  32553. this._framingBehavior = null;
  32554. }
  32555. },
  32556. enumerable: true,
  32557. configurable: true
  32558. });
  32559. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  32560. get: function () {
  32561. return this._autoRotationBehavior;
  32562. },
  32563. enumerable: true,
  32564. configurable: true
  32565. });
  32566. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  32567. get: function () {
  32568. return this._autoRotationBehavior != null;
  32569. },
  32570. set: function (value) {
  32571. if (value === this.useAutoRotationBehavior) {
  32572. return;
  32573. }
  32574. if (value) {
  32575. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  32576. this.addBehavior(this._autoRotationBehavior);
  32577. }
  32578. else {
  32579. this.removeBehavior(this._autoRotationBehavior);
  32580. this._autoRotationBehavior = null;
  32581. }
  32582. },
  32583. enumerable: true,
  32584. configurable: true
  32585. });
  32586. // Cache
  32587. ArcRotateCamera.prototype._initCache = function () {
  32588. _super.prototype._initCache.call(this);
  32589. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32590. this._cache.alpha = undefined;
  32591. this._cache.beta = undefined;
  32592. this._cache.radius = undefined;
  32593. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  32594. };
  32595. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  32596. if (!ignoreParentClass) {
  32597. _super.prototype._updateCache.call(this);
  32598. }
  32599. this._cache._target.copyFrom(this._getTargetPosition());
  32600. this._cache.alpha = this.alpha;
  32601. this._cache.beta = this.beta;
  32602. this._cache.radius = this.radius;
  32603. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  32604. };
  32605. ArcRotateCamera.prototype._getTargetPosition = function () {
  32606. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  32607. var pos = this._targetHost.getAbsolutePosition();
  32608. if (this._targetBoundingCenter) {
  32609. pos.addToRef(this._targetBoundingCenter, this._target);
  32610. }
  32611. else {
  32612. this._target.copyFrom(pos);
  32613. }
  32614. }
  32615. var lockedTargetPosition = this._getLockedTargetPosition();
  32616. if (lockedTargetPosition) {
  32617. return lockedTargetPosition;
  32618. }
  32619. return this._target;
  32620. };
  32621. ArcRotateCamera.prototype.storeState = function () {
  32622. this._storedAlpha = this.alpha;
  32623. this._storedBeta = this.beta;
  32624. this._storedRadius = this.radius;
  32625. this._storedTarget = this._getTargetPosition().clone();
  32626. return _super.prototype.storeState.call(this);
  32627. };
  32628. /**
  32629. * Restored camera state. You must call storeState() first
  32630. */
  32631. ArcRotateCamera.prototype.restoreState = function () {
  32632. if (!_super.prototype.restoreState.call(this)) {
  32633. return false;
  32634. }
  32635. this.alpha = this._storedAlpha;
  32636. this.beta = this._storedBeta;
  32637. this.radius = this._storedRadius;
  32638. this.setTarget(this._storedTarget);
  32639. this.inertialAlphaOffset = 0;
  32640. this.inertialBetaOffset = 0;
  32641. this.inertialRadiusOffset = 0;
  32642. this.inertialPanningX = 0;
  32643. this.inertialPanningY = 0;
  32644. return true;
  32645. };
  32646. // Synchronized
  32647. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  32648. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  32649. return false;
  32650. return this._cache._target.equals(this._getTargetPosition())
  32651. && this._cache.alpha === this.alpha
  32652. && this._cache.beta === this.beta
  32653. && this._cache.radius === this.radius
  32654. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  32655. };
  32656. // Methods
  32657. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  32658. var _this = this;
  32659. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  32660. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  32661. this._useCtrlForPanning = useCtrlForPanning;
  32662. this._panningMouseButton = panningMouseButton;
  32663. this.inputs.attachElement(element, noPreventDefault);
  32664. this._reset = function () {
  32665. _this.inertialAlphaOffset = 0;
  32666. _this.inertialBetaOffset = 0;
  32667. _this.inertialRadiusOffset = 0;
  32668. _this.inertialPanningX = 0;
  32669. _this.inertialPanningY = 0;
  32670. };
  32671. };
  32672. ArcRotateCamera.prototype.detachControl = function (element) {
  32673. this.inputs.detachElement(element);
  32674. if (this._reset) {
  32675. this._reset();
  32676. }
  32677. };
  32678. ArcRotateCamera.prototype._checkInputs = function () {
  32679. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  32680. if (this._collisionTriggered) {
  32681. return;
  32682. }
  32683. this.inputs.checkInputs();
  32684. // Inertia
  32685. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  32686. if (this.getScene().useRightHandedSystem) {
  32687. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32688. }
  32689. else {
  32690. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32691. }
  32692. this.beta += this.inertialBetaOffset;
  32693. this.radius -= this.inertialRadiusOffset;
  32694. this.inertialAlphaOffset *= this.inertia;
  32695. this.inertialBetaOffset *= this.inertia;
  32696. this.inertialRadiusOffset *= this.inertia;
  32697. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  32698. this.inertialAlphaOffset = 0;
  32699. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  32700. this.inertialBetaOffset = 0;
  32701. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  32702. this.inertialRadiusOffset = 0;
  32703. }
  32704. // Panning inertia
  32705. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  32706. if (!this._localDirection) {
  32707. this._localDirection = BABYLON.Vector3.Zero();
  32708. this._transformedDirection = BABYLON.Vector3.Zero();
  32709. }
  32710. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  32711. this._localDirection.multiplyInPlace(this.panningAxis);
  32712. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  32713. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  32714. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  32715. if (!this.panningAxis.y) {
  32716. this._transformedDirection.y = 0;
  32717. }
  32718. if (!this._targetHost) {
  32719. this._target.addInPlace(this._transformedDirection);
  32720. }
  32721. this.inertialPanningX *= this.panningInertia;
  32722. this.inertialPanningY *= this.panningInertia;
  32723. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  32724. this.inertialPanningX = 0;
  32725. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  32726. this.inertialPanningY = 0;
  32727. }
  32728. // Limits
  32729. this._checkLimits();
  32730. _super.prototype._checkInputs.call(this);
  32731. };
  32732. ArcRotateCamera.prototype._checkLimits = function () {
  32733. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  32734. if (this.allowUpsideDown && this.beta > Math.PI) {
  32735. this.beta = this.beta - (2 * Math.PI);
  32736. }
  32737. }
  32738. else {
  32739. if (this.beta < this.lowerBetaLimit) {
  32740. this.beta = this.lowerBetaLimit;
  32741. }
  32742. }
  32743. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  32744. if (this.allowUpsideDown && this.beta < -Math.PI) {
  32745. this.beta = this.beta + (2 * Math.PI);
  32746. }
  32747. }
  32748. else {
  32749. if (this.beta > this.upperBetaLimit) {
  32750. this.beta = this.upperBetaLimit;
  32751. }
  32752. }
  32753. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  32754. this.alpha = this.lowerAlphaLimit;
  32755. }
  32756. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  32757. this.alpha = this.upperAlphaLimit;
  32758. }
  32759. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  32760. this.radius = this.lowerRadiusLimit;
  32761. }
  32762. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  32763. this.radius = this.upperRadiusLimit;
  32764. }
  32765. };
  32766. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  32767. var radiusv3 = this.position.subtract(this._getTargetPosition());
  32768. this.radius = radiusv3.length();
  32769. if (this.radius === 0) {
  32770. this.radius = 0.0001; // Just to avoid division by zero
  32771. }
  32772. // Alpha
  32773. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  32774. if (radiusv3.z < 0) {
  32775. this.alpha = 2 * Math.PI - this.alpha;
  32776. }
  32777. // Beta
  32778. this.beta = Math.acos(radiusv3.y / this.radius);
  32779. this._checkLimits();
  32780. };
  32781. ArcRotateCamera.prototype.setPosition = function (position) {
  32782. if (this.position.equals(position)) {
  32783. return;
  32784. }
  32785. this.position.copyFrom(position);
  32786. this.rebuildAnglesAndRadius();
  32787. };
  32788. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  32789. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  32790. if (allowSamePosition === void 0) { allowSamePosition = false; }
  32791. if (target.getBoundingInfo) {
  32792. if (toBoundingCenter) {
  32793. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  32794. }
  32795. else {
  32796. this._targetBoundingCenter = null;
  32797. }
  32798. this._targetHost = target;
  32799. this._target = this._getTargetPosition();
  32800. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  32801. }
  32802. else {
  32803. var newTarget = target;
  32804. var currentTarget = this._getTargetPosition();
  32805. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  32806. return;
  32807. }
  32808. this._targetHost = null;
  32809. this._target = newTarget;
  32810. this._targetBoundingCenter = null;
  32811. this.onMeshTargetChangedObservable.notifyObservers(null);
  32812. }
  32813. this.rebuildAnglesAndRadius();
  32814. };
  32815. ArcRotateCamera.prototype._getViewMatrix = function () {
  32816. // Compute
  32817. var cosa = Math.cos(this.alpha);
  32818. var sina = Math.sin(this.alpha);
  32819. var cosb = Math.cos(this.beta);
  32820. var sinb = Math.sin(this.beta);
  32821. if (sinb === 0) {
  32822. sinb = 0.0001;
  32823. }
  32824. var target = this._getTargetPosition();
  32825. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  32826. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  32827. if (!this._collider) {
  32828. this._collider = new BABYLON.Collider();
  32829. }
  32830. this._collider.radius = this.collisionRadius;
  32831. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  32832. this._collisionTriggered = true;
  32833. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32834. }
  32835. else {
  32836. this.position.copyFrom(this._newPosition);
  32837. var up = this.upVector;
  32838. if (this.allowUpsideDown && sinb < 0) {
  32839. up = up.clone();
  32840. up = up.negate();
  32841. }
  32842. if (this.getScene().useRightHandedSystem) {
  32843. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  32844. }
  32845. else {
  32846. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  32847. }
  32848. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  32849. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  32850. }
  32851. this._currentTarget = target;
  32852. return this._viewMatrix;
  32853. };
  32854. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  32855. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32856. meshes = meshes || this.getScene().meshes;
  32857. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  32858. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  32859. this.radius = distance * this.zoomOnFactor;
  32860. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  32861. };
  32862. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  32863. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32864. var meshesOrMinMaxVector;
  32865. var distance;
  32866. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  32867. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  32868. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  32869. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  32870. }
  32871. else {
  32872. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  32873. distance = meshesOrMinMaxVectorAndDistance.distance;
  32874. }
  32875. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  32876. if (!doNotUpdateMaxZ) {
  32877. this.maxZ = distance * 2;
  32878. }
  32879. };
  32880. /**
  32881. * @override
  32882. * Override Camera.createRigCamera
  32883. */
  32884. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32885. var alphaShift;
  32886. switch (this.cameraRigMode) {
  32887. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32888. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32889. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32890. case BABYLON.Camera.RIG_MODE_VR:
  32891. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  32892. break;
  32893. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32894. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  32895. break;
  32896. }
  32897. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  32898. rigCam._cameraRigParams = {};
  32899. return rigCam;
  32900. };
  32901. /**
  32902. * @override
  32903. * Override Camera._updateRigCameras
  32904. */
  32905. ArcRotateCamera.prototype._updateRigCameras = function () {
  32906. var camLeft = this._rigCameras[0];
  32907. var camRight = this._rigCameras[1];
  32908. camLeft.beta = camRight.beta = this.beta;
  32909. camLeft.radius = camRight.radius = this.radius;
  32910. switch (this.cameraRigMode) {
  32911. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32912. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32913. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32914. case BABYLON.Camera.RIG_MODE_VR:
  32915. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32916. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32917. break;
  32918. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32919. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32920. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32921. break;
  32922. }
  32923. _super.prototype._updateRigCameras.call(this);
  32924. };
  32925. ArcRotateCamera.prototype.dispose = function () {
  32926. this.inputs.clear();
  32927. _super.prototype.dispose.call(this);
  32928. };
  32929. ArcRotateCamera.prototype.getClassName = function () {
  32930. return "ArcRotateCamera";
  32931. };
  32932. __decorate([
  32933. BABYLON.serialize()
  32934. ], ArcRotateCamera.prototype, "alpha", void 0);
  32935. __decorate([
  32936. BABYLON.serialize()
  32937. ], ArcRotateCamera.prototype, "beta", void 0);
  32938. __decorate([
  32939. BABYLON.serialize()
  32940. ], ArcRotateCamera.prototype, "radius", void 0);
  32941. __decorate([
  32942. BABYLON.serializeAsVector3("target")
  32943. ], ArcRotateCamera.prototype, "_target", void 0);
  32944. __decorate([
  32945. BABYLON.serialize()
  32946. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  32947. __decorate([
  32948. BABYLON.serialize()
  32949. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  32950. __decorate([
  32951. BABYLON.serialize()
  32952. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  32953. __decorate([
  32954. BABYLON.serialize()
  32955. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  32956. __decorate([
  32957. BABYLON.serialize()
  32958. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  32959. __decorate([
  32960. BABYLON.serialize()
  32961. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  32962. __decorate([
  32963. BABYLON.serialize()
  32964. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  32965. __decorate([
  32966. BABYLON.serialize()
  32967. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  32968. __decorate([
  32969. BABYLON.serialize()
  32970. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  32971. __decorate([
  32972. BABYLON.serialize()
  32973. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  32974. __decorate([
  32975. BABYLON.serialize()
  32976. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  32977. __decorate([
  32978. BABYLON.serialize()
  32979. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  32980. __decorate([
  32981. BABYLON.serialize()
  32982. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  32983. __decorate([
  32984. BABYLON.serialize()
  32985. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  32986. return ArcRotateCamera;
  32987. }(BABYLON.TargetCamera));
  32988. BABYLON.ArcRotateCamera = ArcRotateCamera;
  32989. })(BABYLON || (BABYLON = {}));
  32990. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  32991. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  32992. var BABYLON;
  32993. (function (BABYLON) {
  32994. var ArcRotateCameraInputsManager = (function (_super) {
  32995. __extends(ArcRotateCameraInputsManager, _super);
  32996. function ArcRotateCameraInputsManager(camera) {
  32997. return _super.call(this, camera) || this;
  32998. }
  32999. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  33000. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  33001. return this;
  33002. };
  33003. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  33004. this.add(new BABYLON.ArcRotateCameraPointersInput());
  33005. return this;
  33006. };
  33007. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  33008. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  33009. return this;
  33010. };
  33011. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  33012. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  33013. return this;
  33014. };
  33015. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  33016. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  33017. return this;
  33018. };
  33019. return ArcRotateCameraInputsManager;
  33020. }(BABYLON.CameraInputsManager));
  33021. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  33022. })(BABYLON || (BABYLON = {}));
  33023. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  33024. var BABYLON;
  33025. (function (BABYLON) {
  33026. var CubeTexture = (function (_super) {
  33027. __extends(CubeTexture, _super);
  33028. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  33029. if (onLoad === void 0) { onLoad = null; }
  33030. if (onError === void 0) { onError = null; }
  33031. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  33032. if (prefiltered === void 0) { prefiltered = false; }
  33033. if (forcedExtension === void 0) { forcedExtension = null; }
  33034. var _this = _super.call(this, scene) || this;
  33035. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  33036. _this.name = rootUrl;
  33037. _this.url = rootUrl;
  33038. _this._noMipmap = noMipmap;
  33039. _this.hasAlpha = false;
  33040. _this._format = format;
  33041. _this._prefiltered = prefiltered;
  33042. _this.isCube = true;
  33043. _this._textureMatrix = BABYLON.Matrix.Identity();
  33044. if (prefiltered) {
  33045. _this.gammaSpace = false;
  33046. }
  33047. if (!rootUrl && !files) {
  33048. return _this;
  33049. }
  33050. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  33051. if (!files) {
  33052. if (!extensions) {
  33053. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  33054. }
  33055. files = [];
  33056. for (var index = 0; index < extensions.length; index++) {
  33057. files.push(rootUrl + extensions[index]);
  33058. }
  33059. _this._extensions = extensions;
  33060. }
  33061. _this._files = files;
  33062. if (!_this._texture) {
  33063. if (!scene.useDelayedTextureLoading) {
  33064. if (prefiltered) {
  33065. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  33066. }
  33067. else {
  33068. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  33069. }
  33070. }
  33071. else {
  33072. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33073. }
  33074. }
  33075. else if (onLoad) {
  33076. if (_this._texture.isReady) {
  33077. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  33078. }
  33079. else {
  33080. _this._texture.onLoadedObservable.add(onLoad);
  33081. }
  33082. }
  33083. return _this;
  33084. }
  33085. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  33086. return new CubeTexture("", scene, null, noMipmap, files);
  33087. };
  33088. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  33089. if (forcedExtension === void 0) { forcedExtension = null; }
  33090. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  33091. };
  33092. // Methods
  33093. CubeTexture.prototype.delayLoad = function () {
  33094. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33095. return;
  33096. }
  33097. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33098. this._texture = this._getFromCache(this.url, this._noMipmap);
  33099. if (!this._texture) {
  33100. if (this._prefiltered) {
  33101. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  33102. }
  33103. else {
  33104. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  33105. }
  33106. }
  33107. };
  33108. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  33109. return this._textureMatrix;
  33110. };
  33111. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  33112. this._textureMatrix = value;
  33113. };
  33114. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33115. var texture = BABYLON.SerializationHelper.Parse(function () {
  33116. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  33117. }, parsedTexture, scene);
  33118. // Animations
  33119. if (parsedTexture.animations) {
  33120. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  33121. var parsedAnimation = parsedTexture.animations[animationIndex];
  33122. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33123. }
  33124. }
  33125. return texture;
  33126. };
  33127. CubeTexture.prototype.clone = function () {
  33128. var _this = this;
  33129. return BABYLON.SerializationHelper.Clone(function () {
  33130. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  33131. }, this);
  33132. };
  33133. return CubeTexture;
  33134. }(BABYLON.BaseTexture));
  33135. BABYLON.CubeTexture = CubeTexture;
  33136. })(BABYLON || (BABYLON = {}));
  33137. //# sourceMappingURL=babylon.cubeTexture.js.map
  33138. var BABYLON;
  33139. (function (BABYLON) {
  33140. var RenderTargetTexture = (function (_super) {
  33141. __extends(RenderTargetTexture, _super);
  33142. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  33143. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  33144. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33145. if (isCube === void 0) { isCube = false; }
  33146. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33147. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  33148. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  33149. if (isMulti === void 0) { isMulti = false; }
  33150. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  33151. _this.isCube = isCube;
  33152. /**
  33153. * Use this list to define the list of mesh you want to render.
  33154. */
  33155. _this.renderList = new Array();
  33156. _this.renderParticles = true;
  33157. _this.renderSprites = false;
  33158. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  33159. _this.ignoreCameraViewport = false;
  33160. // Events
  33161. /**
  33162. * An event triggered when the texture is unbind.
  33163. * @type {BABYLON.Observable}
  33164. */
  33165. _this.onBeforeBindObservable = new BABYLON.Observable();
  33166. /**
  33167. * An event triggered when the texture is unbind.
  33168. * @type {BABYLON.Observable}
  33169. */
  33170. _this.onAfterUnbindObservable = new BABYLON.Observable();
  33171. /**
  33172. * An event triggered before rendering the texture
  33173. * @type {BABYLON.Observable}
  33174. */
  33175. _this.onBeforeRenderObservable = new BABYLON.Observable();
  33176. /**
  33177. * An event triggered after rendering the texture
  33178. * @type {BABYLON.Observable}
  33179. */
  33180. _this.onAfterRenderObservable = new BABYLON.Observable();
  33181. /**
  33182. * An event triggered after the texture clear
  33183. * @type {BABYLON.Observable}
  33184. */
  33185. _this.onClearObservable = new BABYLON.Observable();
  33186. _this._currentRefreshId = -1;
  33187. _this._refreshRate = 1;
  33188. _this._samples = 1;
  33189. scene = _this.getScene();
  33190. _this.name = name;
  33191. _this.isRenderTarget = true;
  33192. _this._size = size;
  33193. _this._generateMipMaps = generateMipMaps;
  33194. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  33195. // Rendering groups
  33196. _this._renderingManager = new BABYLON.RenderingManager(scene);
  33197. if (isMulti) {
  33198. return _this;
  33199. }
  33200. _this._renderTargetOptions = {
  33201. generateMipMaps: generateMipMaps,
  33202. type: type,
  33203. samplingMode: samplingMode,
  33204. generateDepthBuffer: generateDepthBuffer,
  33205. generateStencilBuffer: generateStencilBuffer
  33206. };
  33207. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  33208. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33209. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33210. }
  33211. if (isCube) {
  33212. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  33213. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  33214. _this._textureMatrix = BABYLON.Matrix.Identity();
  33215. }
  33216. else {
  33217. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  33218. }
  33219. return _this;
  33220. }
  33221. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  33222. get: function () {
  33223. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  33224. },
  33225. enumerable: true,
  33226. configurable: true
  33227. });
  33228. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  33229. get: function () {
  33230. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  33231. },
  33232. enumerable: true,
  33233. configurable: true
  33234. });
  33235. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  33236. get: function () {
  33237. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  33238. },
  33239. enumerable: true,
  33240. configurable: true
  33241. });
  33242. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  33243. set: function (callback) {
  33244. if (this._onAfterUnbindObserver) {
  33245. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  33246. }
  33247. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  33248. },
  33249. enumerable: true,
  33250. configurable: true
  33251. });
  33252. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  33253. set: function (callback) {
  33254. if (this._onBeforeRenderObserver) {
  33255. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  33256. }
  33257. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  33258. },
  33259. enumerable: true,
  33260. configurable: true
  33261. });
  33262. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  33263. set: function (callback) {
  33264. if (this._onAfterRenderObserver) {
  33265. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  33266. }
  33267. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  33268. },
  33269. enumerable: true,
  33270. configurable: true
  33271. });
  33272. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  33273. set: function (callback) {
  33274. if (this._onClearObserver) {
  33275. this.onClearObservable.remove(this._onClearObserver);
  33276. }
  33277. this._onClearObserver = this.onClearObservable.add(callback);
  33278. },
  33279. enumerable: true,
  33280. configurable: true
  33281. });
  33282. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  33283. get: function () {
  33284. return this._renderTargetOptions;
  33285. },
  33286. enumerable: true,
  33287. configurable: true
  33288. });
  33289. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  33290. get: function () {
  33291. return this._samples;
  33292. },
  33293. set: function (value) {
  33294. if (this._samples === value) {
  33295. return;
  33296. }
  33297. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  33298. },
  33299. enumerable: true,
  33300. configurable: true
  33301. });
  33302. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  33303. this._currentRefreshId = -1;
  33304. };
  33305. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  33306. get: function () {
  33307. return this._refreshRate;
  33308. },
  33309. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  33310. set: function (value) {
  33311. this._refreshRate = value;
  33312. this.resetRefreshCounter();
  33313. },
  33314. enumerable: true,
  33315. configurable: true
  33316. });
  33317. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  33318. if (!this._postProcessManager) {
  33319. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  33320. this._postProcesses = new Array();
  33321. }
  33322. this._postProcesses.push(postProcess);
  33323. this._postProcesses[0].autoClear = false;
  33324. };
  33325. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  33326. if (!this._postProcesses) {
  33327. return;
  33328. }
  33329. if (dispose) {
  33330. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  33331. var postProcess = _a[_i];
  33332. postProcess.dispose();
  33333. postProcess = null;
  33334. }
  33335. }
  33336. this._postProcesses = [];
  33337. };
  33338. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  33339. if (!this._postProcesses) {
  33340. return;
  33341. }
  33342. var index = this._postProcesses.indexOf(postProcess);
  33343. if (index === -1) {
  33344. return;
  33345. }
  33346. this._postProcesses.splice(index, 1);
  33347. if (this._postProcesses.length > 0) {
  33348. this._postProcesses[0].autoClear = false;
  33349. }
  33350. };
  33351. RenderTargetTexture.prototype._shouldRender = function () {
  33352. if (this._currentRefreshId === -1) {
  33353. this._currentRefreshId = 1;
  33354. return true;
  33355. }
  33356. if (this.refreshRate === this._currentRefreshId) {
  33357. this._currentRefreshId = 1;
  33358. return true;
  33359. }
  33360. this._currentRefreshId++;
  33361. return false;
  33362. };
  33363. RenderTargetTexture.prototype.getRenderSize = function () {
  33364. return this._size;
  33365. };
  33366. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  33367. get: function () {
  33368. return true;
  33369. },
  33370. enumerable: true,
  33371. configurable: true
  33372. });
  33373. RenderTargetTexture.prototype.scale = function (ratio) {
  33374. var newSize = this._size * ratio;
  33375. this.resize(newSize);
  33376. };
  33377. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  33378. if (this.isCube) {
  33379. return this._textureMatrix;
  33380. }
  33381. return _super.prototype.getReflectionTextureMatrix.call(this);
  33382. };
  33383. RenderTargetTexture.prototype.resize = function (size) {
  33384. this.releaseInternalTexture();
  33385. if (this.isCube) {
  33386. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  33387. }
  33388. else {
  33389. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  33390. }
  33391. };
  33392. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  33393. var scene = this.getScene();
  33394. var engine = scene.getEngine();
  33395. if (this.useCameraPostProcesses !== undefined) {
  33396. useCameraPostProcess = this.useCameraPostProcesses;
  33397. }
  33398. if (this._waitingRenderList) {
  33399. this.renderList = [];
  33400. for (var index = 0; index < this._waitingRenderList.length; index++) {
  33401. var id = this._waitingRenderList[index];
  33402. this.renderList.push(scene.getMeshByID(id));
  33403. }
  33404. delete this._waitingRenderList;
  33405. }
  33406. // Is predicate defined?
  33407. if (this.renderListPredicate) {
  33408. this.renderList.splice(0); // Clear previous renderList
  33409. var sceneMeshes = this.getScene().meshes;
  33410. for (var index = 0; index < sceneMeshes.length; index++) {
  33411. var mesh = sceneMeshes[index];
  33412. if (this.renderListPredicate(mesh)) {
  33413. this.renderList.push(mesh);
  33414. }
  33415. }
  33416. }
  33417. if (this.renderList && this.renderList.length === 0) {
  33418. return;
  33419. }
  33420. this.onBeforeBindObservable.notifyObservers(this);
  33421. // Set custom projection.
  33422. // Needs to be before binding to prevent changing the aspect ratio.
  33423. var camera;
  33424. if (this.activeCamera) {
  33425. camera = this.activeCamera;
  33426. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  33427. if (this.activeCamera !== scene.activeCamera) {
  33428. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  33429. }
  33430. }
  33431. else {
  33432. camera = scene.activeCamera;
  33433. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  33434. }
  33435. // Prepare renderingManager
  33436. this._renderingManager.reset();
  33437. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  33438. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  33439. var sceneRenderId = scene.getRenderId();
  33440. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  33441. var mesh = currentRenderList[meshIndex];
  33442. if (mesh) {
  33443. if (!mesh.isReady()) {
  33444. // Reset _currentRefreshId
  33445. this.resetRefreshCounter();
  33446. continue;
  33447. }
  33448. mesh._preActivateForIntermediateRendering(sceneRenderId);
  33449. var isMasked = void 0;
  33450. if (!this.renderList) {
  33451. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  33452. }
  33453. else {
  33454. isMasked = false;
  33455. }
  33456. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  33457. mesh._activate(sceneRenderId);
  33458. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33459. var subMesh = mesh.subMeshes[subIndex];
  33460. scene._activeIndices.addCount(subMesh.indexCount, false);
  33461. this._renderingManager.dispatch(subMesh);
  33462. }
  33463. }
  33464. }
  33465. }
  33466. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  33467. var particleSystem = scene.particleSystems[particleIndex];
  33468. var emitter = particleSystem.emitter;
  33469. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  33470. continue;
  33471. }
  33472. if (currentRenderList.indexOf(emitter) >= 0) {
  33473. this._renderingManager.dispatchParticles(particleSystem);
  33474. }
  33475. }
  33476. if (this.isCube) {
  33477. for (var face = 0; face < 6; face++) {
  33478. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  33479. scene.incrementRenderId();
  33480. scene.resetCachedMaterial();
  33481. }
  33482. }
  33483. else {
  33484. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  33485. }
  33486. this.onAfterUnbindObservable.notifyObservers(this);
  33487. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  33488. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  33489. }
  33490. engine.setViewport(scene.activeCamera.viewport);
  33491. scene.resetCachedMaterial();
  33492. };
  33493. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  33494. var _this = this;
  33495. var scene = this.getScene();
  33496. var engine = scene.getEngine();
  33497. // Bind
  33498. if (this._postProcessManager) {
  33499. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  33500. }
  33501. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  33502. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  33503. }
  33504. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  33505. // Clear
  33506. if (this.onClearObservable.hasObservers()) {
  33507. this.onClearObservable.notifyObservers(engine);
  33508. }
  33509. else {
  33510. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  33511. }
  33512. if (!this._doNotChangeAspectRatio) {
  33513. scene.updateTransformMatrix(true);
  33514. }
  33515. // Render
  33516. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  33517. if (this._postProcessManager) {
  33518. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  33519. }
  33520. else if (useCameraPostProcess) {
  33521. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  33522. }
  33523. if (!this._doNotChangeAspectRatio) {
  33524. scene.updateTransformMatrix(true);
  33525. }
  33526. // Dump ?
  33527. if (dumpForDebug) {
  33528. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  33529. }
  33530. // Unbind
  33531. if (!this.isCube || faceIndex === 5) {
  33532. if (this.isCube) {
  33533. if (faceIndex === 5) {
  33534. engine.generateMipMapsForCubemap(this._texture);
  33535. }
  33536. }
  33537. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  33538. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  33539. });
  33540. }
  33541. else {
  33542. this.onAfterRenderObservable.notifyObservers(faceIndex);
  33543. }
  33544. };
  33545. /**
  33546. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  33547. * This allowed control for front to back rendering or reversly depending of the special needs.
  33548. *
  33549. * @param renderingGroupId The rendering group id corresponding to its index
  33550. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  33551. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  33552. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  33553. */
  33554. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  33555. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  33556. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  33557. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  33558. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  33559. };
  33560. /**
  33561. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  33562. *
  33563. * @param renderingGroupId The rendering group id corresponding to its index
  33564. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  33565. */
  33566. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  33567. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  33568. };
  33569. RenderTargetTexture.prototype.clone = function () {
  33570. var textureSize = this.getSize();
  33571. 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);
  33572. // Base texture
  33573. newTexture.hasAlpha = this.hasAlpha;
  33574. newTexture.level = this.level;
  33575. // RenderTarget Texture
  33576. newTexture.coordinatesMode = this.coordinatesMode;
  33577. newTexture.renderList = this.renderList.slice(0);
  33578. return newTexture;
  33579. };
  33580. RenderTargetTexture.prototype.serialize = function () {
  33581. if (!this.name) {
  33582. return null;
  33583. }
  33584. var serializationObject = _super.prototype.serialize.call(this);
  33585. serializationObject.renderTargetSize = this.getRenderSize();
  33586. serializationObject.renderList = [];
  33587. for (var index = 0; index < this.renderList.length; index++) {
  33588. serializationObject.renderList.push(this.renderList[index].id);
  33589. }
  33590. return serializationObject;
  33591. };
  33592. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  33593. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  33594. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  33595. };
  33596. RenderTargetTexture.prototype.dispose = function () {
  33597. if (this._postProcessManager) {
  33598. this._postProcessManager.dispose();
  33599. this._postProcessManager = null;
  33600. }
  33601. this.clearPostProcesses(true);
  33602. this.renderList = null;
  33603. // Remove from custom render targets
  33604. var scene = this.getScene();
  33605. var index = scene.customRenderTargets.indexOf(this);
  33606. if (index >= 0) {
  33607. scene.customRenderTargets.splice(index, 1);
  33608. }
  33609. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  33610. var camera = _a[_i];
  33611. index = camera.customRenderTargets.indexOf(this);
  33612. if (index >= 0) {
  33613. camera.customRenderTargets.splice(index, 1);
  33614. }
  33615. }
  33616. _super.prototype.dispose.call(this);
  33617. };
  33618. RenderTargetTexture.prototype._rebuild = function () {
  33619. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  33620. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  33621. }
  33622. if (this._postProcessManager) {
  33623. this._postProcessManager._rebuild();
  33624. }
  33625. };
  33626. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  33627. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  33628. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  33629. return RenderTargetTexture;
  33630. }(BABYLON.Texture));
  33631. BABYLON.RenderTargetTexture = RenderTargetTexture;
  33632. })(BABYLON || (BABYLON = {}));
  33633. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  33634. var BABYLON;
  33635. (function (BABYLON) {
  33636. ;
  33637. var MultiRenderTarget = (function (_super) {
  33638. __extends(MultiRenderTarget, _super);
  33639. function MultiRenderTarget(name, size, count, scene, options) {
  33640. var _this = this;
  33641. options = options || {};
  33642. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  33643. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  33644. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  33645. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  33646. if (!_this.isSupported) {
  33647. _this.dispose();
  33648. return;
  33649. }
  33650. var types = [];
  33651. var samplingModes = [];
  33652. for (var i = 0; i < count; i++) {
  33653. if (options.types && options.types[i]) {
  33654. types.push(options.types[i]);
  33655. }
  33656. else {
  33657. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  33658. }
  33659. if (options.samplingModes && options.samplingModes[i]) {
  33660. samplingModes.push(options.samplingModes[i]);
  33661. }
  33662. else {
  33663. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33664. }
  33665. }
  33666. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  33667. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  33668. _this._count = count;
  33669. _this._size = size;
  33670. _this._multiRenderTargetOptions = {
  33671. samplingModes: samplingModes,
  33672. generateMipMaps: generateMipMaps,
  33673. generateDepthBuffer: generateDepthBuffer,
  33674. generateStencilBuffer: generateStencilBuffer,
  33675. generateDepthTexture: generateDepthTexture,
  33676. types: types,
  33677. textureCount: count
  33678. };
  33679. _this._createInternalTextures();
  33680. _this._createTextures();
  33681. return _this;
  33682. }
  33683. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  33684. get: function () {
  33685. var engine = this.getScene().getEngine();
  33686. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  33687. },
  33688. enumerable: true,
  33689. configurable: true
  33690. });
  33691. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  33692. get: function () {
  33693. return this._textures;
  33694. },
  33695. enumerable: true,
  33696. configurable: true
  33697. });
  33698. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  33699. get: function () {
  33700. return this._textures[this._textures.length - 1];
  33701. },
  33702. enumerable: true,
  33703. configurable: true
  33704. });
  33705. MultiRenderTarget.prototype._rebuild = function () {
  33706. this.releaseInternalTextures();
  33707. this._createInternalTextures();
  33708. for (var i = 0; i < this._internalTextures.length; i++) {
  33709. var texture = this._textures[i];
  33710. texture._texture = this._internalTextures[i];
  33711. }
  33712. // Keeps references to frame buffer and stencil/depth buffer
  33713. this._texture = this._internalTextures[0];
  33714. };
  33715. MultiRenderTarget.prototype._createInternalTextures = function () {
  33716. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  33717. };
  33718. MultiRenderTarget.prototype._createTextures = function () {
  33719. this._textures = [];
  33720. for (var i = 0; i < this._internalTextures.length; i++) {
  33721. var texture = new BABYLON.Texture(null, this.getScene());
  33722. texture._texture = this._internalTextures[i];
  33723. this._textures.push(texture);
  33724. }
  33725. // Keeps references to frame buffer and stencil/depth buffer
  33726. this._texture = this._internalTextures[0];
  33727. };
  33728. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  33729. get: function () {
  33730. return this._samples;
  33731. },
  33732. set: function (value) {
  33733. if (this._samples === value) {
  33734. return;
  33735. }
  33736. for (var i = 0; i < this._internalTextures.length; i++) {
  33737. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  33738. }
  33739. },
  33740. enumerable: true,
  33741. configurable: true
  33742. });
  33743. MultiRenderTarget.prototype.resize = function (size) {
  33744. this.releaseInternalTextures();
  33745. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  33746. this._createInternalTextures();
  33747. };
  33748. MultiRenderTarget.prototype.dispose = function () {
  33749. this.releaseInternalTextures();
  33750. _super.prototype.dispose.call(this);
  33751. };
  33752. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  33753. if (!this._internalTextures) {
  33754. return;
  33755. }
  33756. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  33757. if (this._internalTextures[i] !== undefined) {
  33758. this._internalTextures[i].dispose();
  33759. this._internalTextures.splice(i, 1);
  33760. }
  33761. }
  33762. };
  33763. return MultiRenderTarget;
  33764. }(BABYLON.RenderTargetTexture));
  33765. BABYLON.MultiRenderTarget = MultiRenderTarget;
  33766. })(BABYLON || (BABYLON = {}));
  33767. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  33768. /// <reference path="babylon.renderTargetTexture.ts" />
  33769. var BABYLON;
  33770. (function (BABYLON) {
  33771. var MirrorTexture = (function (_super) {
  33772. __extends(MirrorTexture, _super);
  33773. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  33774. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33775. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33776. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  33777. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  33778. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  33779. _this._transformMatrix = BABYLON.Matrix.Zero();
  33780. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  33781. _this._blurKernelX = 0;
  33782. _this._blurKernelY = 0;
  33783. _this._blurRatio = 1.0;
  33784. _this.onBeforeRenderObservable.add(function () {
  33785. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  33786. _this._savedViewMatrix = scene.getViewMatrix();
  33787. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  33788. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  33789. scene.clipPlane = _this.mirrorPlane;
  33790. scene.getEngine().cullBackFaces = false;
  33791. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  33792. });
  33793. _this.onAfterRenderObservable.add(function () {
  33794. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  33795. scene.getEngine().cullBackFaces = true;
  33796. scene._mirroredCameraPosition = null;
  33797. delete scene.clipPlane;
  33798. });
  33799. return _this;
  33800. }
  33801. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  33802. get: function () {
  33803. return this._blurRatio;
  33804. },
  33805. set: function (value) {
  33806. if (this._blurRatio === value) {
  33807. return;
  33808. }
  33809. this._blurRatio = value;
  33810. this._preparePostProcesses();
  33811. },
  33812. enumerable: true,
  33813. configurable: true
  33814. });
  33815. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  33816. set: function (value) {
  33817. this.blurKernelX = value;
  33818. this.blurKernelY = value;
  33819. },
  33820. enumerable: true,
  33821. configurable: true
  33822. });
  33823. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  33824. get: function () {
  33825. return this._blurKernelX;
  33826. },
  33827. set: function (value) {
  33828. if (this._blurKernelX === value) {
  33829. return;
  33830. }
  33831. this._blurKernelX = value;
  33832. this._preparePostProcesses();
  33833. },
  33834. enumerable: true,
  33835. configurable: true
  33836. });
  33837. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  33838. get: function () {
  33839. return this._blurKernelY;
  33840. },
  33841. set: function (value) {
  33842. if (this._blurKernelY === value) {
  33843. return;
  33844. }
  33845. this._blurKernelY = value;
  33846. this._preparePostProcesses();
  33847. },
  33848. enumerable: true,
  33849. configurable: true
  33850. });
  33851. MirrorTexture.prototype._preparePostProcesses = function () {
  33852. this.clearPostProcesses(true);
  33853. if (this._blurKernelX && this._blurKernelY) {
  33854. var engine = this.getScene().getEngine();
  33855. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33856. 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);
  33857. this._blurX.autoClear = false;
  33858. if (this._blurRatio === 1 && this.samples < 2) {
  33859. this._blurX.outputTexture = this._texture;
  33860. }
  33861. else {
  33862. this._blurX.alwaysForcePOT = true;
  33863. }
  33864. 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);
  33865. this._blurY.autoClear = false;
  33866. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  33867. this.addPostProcess(this._blurX);
  33868. this.addPostProcess(this._blurY);
  33869. }
  33870. };
  33871. MirrorTexture.prototype.clone = function () {
  33872. var textureSize = this.getSize();
  33873. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  33874. // Base texture
  33875. newTexture.hasAlpha = this.hasAlpha;
  33876. newTexture.level = this.level;
  33877. // Mirror Texture
  33878. newTexture.mirrorPlane = this.mirrorPlane.clone();
  33879. newTexture.renderList = this.renderList.slice(0);
  33880. return newTexture;
  33881. };
  33882. MirrorTexture.prototype.serialize = function () {
  33883. if (!this.name) {
  33884. return null;
  33885. }
  33886. var serializationObject = _super.prototype.serialize.call(this);
  33887. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  33888. return serializationObject;
  33889. };
  33890. return MirrorTexture;
  33891. }(BABYLON.RenderTargetTexture));
  33892. BABYLON.MirrorTexture = MirrorTexture;
  33893. })(BABYLON || (BABYLON = {}));
  33894. //# sourceMappingURL=babylon.mirrorTexture.js.map
  33895. /// <reference path="babylon.renderTargetTexture.ts" />
  33896. var BABYLON;
  33897. (function (BABYLON) {
  33898. /**
  33899. * Creates a refraction texture used by refraction channel of the standard material.
  33900. * @param name the texture name
  33901. * @param size size of the underlying texture
  33902. * @param scene root scene
  33903. */
  33904. var RefractionTexture = (function (_super) {
  33905. __extends(RefractionTexture, _super);
  33906. function RefractionTexture(name, size, scene, generateMipMaps) {
  33907. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  33908. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  33909. _this.depth = 2.0;
  33910. _this.onBeforeRenderObservable.add(function () {
  33911. scene.clipPlane = _this.refractionPlane;
  33912. });
  33913. _this.onAfterRenderObservable.add(function () {
  33914. delete scene.clipPlane;
  33915. });
  33916. return _this;
  33917. }
  33918. RefractionTexture.prototype.clone = function () {
  33919. var textureSize = this.getSize();
  33920. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  33921. // Base texture
  33922. newTexture.hasAlpha = this.hasAlpha;
  33923. newTexture.level = this.level;
  33924. // Refraction Texture
  33925. newTexture.refractionPlane = this.refractionPlane.clone();
  33926. newTexture.renderList = this.renderList.slice(0);
  33927. newTexture.depth = this.depth;
  33928. return newTexture;
  33929. };
  33930. RefractionTexture.prototype.serialize = function () {
  33931. if (!this.name) {
  33932. return null;
  33933. }
  33934. var serializationObject = _super.prototype.serialize.call(this);
  33935. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  33936. serializationObject.depth = this.depth;
  33937. return serializationObject;
  33938. };
  33939. return RefractionTexture;
  33940. }(BABYLON.RenderTargetTexture));
  33941. BABYLON.RefractionTexture = RefractionTexture;
  33942. })(BABYLON || (BABYLON = {}));
  33943. //# sourceMappingURL=babylon.refractionTexture.js.map
  33944. /// <reference path="babylon.texture.ts" />
  33945. var BABYLON;
  33946. (function (BABYLON) {
  33947. var DynamicTexture = (function (_super) {
  33948. __extends(DynamicTexture, _super);
  33949. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  33950. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33951. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  33952. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  33953. _this.name = name;
  33954. var engine = _this.getScene().getEngine();
  33955. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33956. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33957. _this._generateMipMaps = generateMipMaps;
  33958. if (options.getContext) {
  33959. _this._canvas = options;
  33960. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33961. }
  33962. else {
  33963. _this._canvas = document.createElement("canvas");
  33964. if (options.width) {
  33965. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33966. }
  33967. else {
  33968. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  33969. }
  33970. }
  33971. var textureSize = _this.getSize();
  33972. _this._canvas.width = textureSize.width;
  33973. _this._canvas.height = textureSize.height;
  33974. _this._context = _this._canvas.getContext("2d");
  33975. return _this;
  33976. }
  33977. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  33978. get: function () {
  33979. return true;
  33980. },
  33981. enumerable: true,
  33982. configurable: true
  33983. });
  33984. DynamicTexture.prototype._recreate = function (textureSize) {
  33985. this._canvas.width = textureSize.width;
  33986. this._canvas.height = textureSize.height;
  33987. this.releaseInternalTexture();
  33988. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  33989. };
  33990. DynamicTexture.prototype.scale = function (ratio) {
  33991. var textureSize = this.getSize();
  33992. textureSize.width *= ratio;
  33993. textureSize.height *= ratio;
  33994. this._recreate(textureSize);
  33995. };
  33996. DynamicTexture.prototype.scaleTo = function (width, height) {
  33997. var textureSize = this.getSize();
  33998. textureSize.width = width;
  33999. textureSize.height = height;
  34000. this._recreate(textureSize);
  34001. };
  34002. DynamicTexture.prototype.getContext = function () {
  34003. return this._context;
  34004. };
  34005. DynamicTexture.prototype.clear = function () {
  34006. var size = this.getSize();
  34007. this._context.fillRect(0, 0, size.width, size.height);
  34008. };
  34009. DynamicTexture.prototype.update = function (invertY) {
  34010. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  34011. };
  34012. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  34013. if (update === void 0) { update = true; }
  34014. var size = this.getSize();
  34015. if (clearColor) {
  34016. this._context.fillStyle = clearColor;
  34017. this._context.fillRect(0, 0, size.width, size.height);
  34018. }
  34019. this._context.font = font;
  34020. if (x === null || x === undefined) {
  34021. var textSize = this._context.measureText(text);
  34022. x = (size.width - textSize.width) / 2;
  34023. }
  34024. if (y === null || y === undefined) {
  34025. var fontSize = parseInt((font.replace(/\D/g, '')));
  34026. ;
  34027. y = (size.height / 2) + (fontSize / 3.65);
  34028. }
  34029. this._context.fillStyle = color;
  34030. this._context.fillText(text, x, y);
  34031. if (update) {
  34032. this.update(invertY);
  34033. }
  34034. };
  34035. DynamicTexture.prototype.clone = function () {
  34036. var textureSize = this.getSize();
  34037. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  34038. // Base texture
  34039. newTexture.hasAlpha = this.hasAlpha;
  34040. newTexture.level = this.level;
  34041. // Dynamic Texture
  34042. newTexture.wrapU = this.wrapU;
  34043. newTexture.wrapV = this.wrapV;
  34044. return newTexture;
  34045. };
  34046. DynamicTexture.prototype._rebuild = function () {
  34047. this.update();
  34048. };
  34049. return DynamicTexture;
  34050. }(BABYLON.Texture));
  34051. BABYLON.DynamicTexture = DynamicTexture;
  34052. })(BABYLON || (BABYLON = {}));
  34053. //# sourceMappingURL=babylon.dynamicTexture.js.map
  34054. var BABYLON;
  34055. (function (BABYLON) {
  34056. var VideoTexture = (function (_super) {
  34057. __extends(VideoTexture, _super);
  34058. /**
  34059. * Creates a video texture.
  34060. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  34061. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  34062. * @param {BABYLON.Scene} scene is obviously the current scene.
  34063. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  34064. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  34065. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  34066. */
  34067. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  34068. if (generateMipMaps === void 0) { generateMipMaps = false; }
  34069. if (invertY === void 0) { invertY = false; }
  34070. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34071. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  34072. _this._autoLaunch = true;
  34073. var urls;
  34074. _this.name = name;
  34075. if (urlsOrVideo instanceof HTMLVideoElement) {
  34076. _this.video = urlsOrVideo;
  34077. }
  34078. else {
  34079. urls = urlsOrVideo;
  34080. _this.video = document.createElement("video");
  34081. _this.video.autoplay = false;
  34082. _this.video.loop = true;
  34083. }
  34084. _this._generateMipMaps = generateMipMaps;
  34085. _this._samplingMode = samplingMode;
  34086. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  34087. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34088. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34089. }
  34090. else {
  34091. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34092. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34093. _this._generateMipMaps = false;
  34094. }
  34095. if (urls) {
  34096. _this.video.addEventListener("canplay", function () {
  34097. _this._createTexture();
  34098. });
  34099. urls.forEach(function (url) {
  34100. var source = document.createElement("source");
  34101. source.src = url;
  34102. _this.video.appendChild(source);
  34103. });
  34104. }
  34105. else {
  34106. _this._createTexture();
  34107. }
  34108. _this._lastUpdate = BABYLON.Tools.Now;
  34109. return _this;
  34110. }
  34111. VideoTexture.prototype.__setTextureReady = function () {
  34112. this._texture.isReady = true;
  34113. };
  34114. VideoTexture.prototype._createTexture = function () {
  34115. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  34116. if (this._autoLaunch) {
  34117. this._autoLaunch = false;
  34118. this.video.play();
  34119. }
  34120. this._setTextureReady = this.__setTextureReady.bind(this);
  34121. this.video.addEventListener("playing", this._setTextureReady);
  34122. };
  34123. VideoTexture.prototype._rebuild = function () {
  34124. this.update();
  34125. };
  34126. VideoTexture.prototype.update = function () {
  34127. var now = BABYLON.Tools.Now;
  34128. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  34129. return false;
  34130. }
  34131. this._lastUpdate = now;
  34132. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  34133. return true;
  34134. };
  34135. VideoTexture.prototype.dispose = function () {
  34136. _super.prototype.dispose.call(this);
  34137. this.video.removeEventListener("playing", this._setTextureReady);
  34138. };
  34139. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  34140. var video = document.createElement("video");
  34141. var constraintsDeviceId;
  34142. if (constraints && constraints.deviceId) {
  34143. constraintsDeviceId = {
  34144. exact: constraints.deviceId
  34145. };
  34146. }
  34147. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  34148. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  34149. if (navigator.getUserMedia) {
  34150. navigator.getUserMedia({
  34151. video: {
  34152. deviceId: constraintsDeviceId,
  34153. width: {
  34154. min: (constraints && constraints.minWidth) || 256,
  34155. max: (constraints && constraints.maxWidth) || 640
  34156. },
  34157. height: {
  34158. min: (constraints && constraints.minHeight) || 256,
  34159. max: (constraints && constraints.maxHeight) || 480
  34160. }
  34161. }
  34162. }, function (stream) {
  34163. if (video.mozSrcObject !== undefined) {
  34164. video.mozSrcObject = stream;
  34165. }
  34166. else {
  34167. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  34168. }
  34169. video.play();
  34170. if (onReady) {
  34171. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  34172. }
  34173. }, function (e) {
  34174. BABYLON.Tools.Error(e.name);
  34175. });
  34176. }
  34177. };
  34178. return VideoTexture;
  34179. }(BABYLON.Texture));
  34180. BABYLON.VideoTexture = VideoTexture;
  34181. })(BABYLON || (BABYLON = {}));
  34182. //# sourceMappingURL=babylon.videoTexture.js.map
  34183. var BABYLON;
  34184. (function (BABYLON) {
  34185. var RawTexture = (function (_super) {
  34186. __extends(RawTexture, _super);
  34187. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  34188. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34189. if (invertY === void 0) { invertY = false; }
  34190. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34191. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  34192. _this.format = format;
  34193. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  34194. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34195. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34196. return _this;
  34197. }
  34198. RawTexture.prototype.update = function (data) {
  34199. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  34200. };
  34201. // Statics
  34202. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34203. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34204. if (invertY === void 0) { invertY = false; }
  34205. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34206. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  34207. };
  34208. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34209. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34210. if (invertY === void 0) { invertY = false; }
  34211. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34212. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34213. };
  34214. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34215. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34216. if (invertY === void 0) { invertY = false; }
  34217. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34218. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34219. };
  34220. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34221. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34222. if (invertY === void 0) { invertY = false; }
  34223. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34224. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  34225. };
  34226. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34227. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34228. if (invertY === void 0) { invertY = false; }
  34229. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34230. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  34231. };
  34232. return RawTexture;
  34233. }(BABYLON.Texture));
  34234. BABYLON.RawTexture = RawTexture;
  34235. })(BABYLON || (BABYLON = {}));
  34236. //# sourceMappingURL=babylon.rawTexture.js.map
  34237. var BABYLON;
  34238. (function (BABYLON) {
  34239. var Internals;
  34240. (function (Internals) {
  34241. /*
  34242. * Based on jsTGALoader - Javascript loader for TGA file
  34243. * By Vincent Thibault
  34244. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  34245. */
  34246. var TGATools = (function () {
  34247. function TGATools() {
  34248. }
  34249. TGATools.GetTGAHeader = function (data) {
  34250. var offset = 0;
  34251. var header = {
  34252. id_length: data[offset++],
  34253. colormap_type: data[offset++],
  34254. image_type: data[offset++],
  34255. colormap_index: data[offset++] | data[offset++] << 8,
  34256. colormap_length: data[offset++] | data[offset++] << 8,
  34257. colormap_size: data[offset++],
  34258. origin: [
  34259. data[offset++] | data[offset++] << 8,
  34260. data[offset++] | data[offset++] << 8
  34261. ],
  34262. width: data[offset++] | data[offset++] << 8,
  34263. height: data[offset++] | data[offset++] << 8,
  34264. pixel_size: data[offset++],
  34265. flags: data[offset++]
  34266. };
  34267. return header;
  34268. };
  34269. TGATools.UploadContent = function (gl, data) {
  34270. // Not enough data to contain header ?
  34271. if (data.length < 19) {
  34272. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  34273. return;
  34274. }
  34275. // Read Header
  34276. var offset = 18;
  34277. var header = TGATools.GetTGAHeader(data);
  34278. // Assume it's a valid Targa file.
  34279. if (header.id_length + offset > data.length) {
  34280. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  34281. return;
  34282. }
  34283. // Skip not needed data
  34284. offset += header.id_length;
  34285. var use_rle = false;
  34286. var use_pal = false;
  34287. var use_rgb = false;
  34288. var use_grey = false;
  34289. // Get some informations.
  34290. switch (header.image_type) {
  34291. case TGATools._TYPE_RLE_INDEXED:
  34292. use_rle = true;
  34293. case TGATools._TYPE_INDEXED:
  34294. use_pal = true;
  34295. break;
  34296. case TGATools._TYPE_RLE_RGB:
  34297. use_rle = true;
  34298. case TGATools._TYPE_RGB:
  34299. use_rgb = true;
  34300. break;
  34301. case TGATools._TYPE_RLE_GREY:
  34302. use_rle = true;
  34303. case TGATools._TYPE_GREY:
  34304. use_grey = true;
  34305. break;
  34306. }
  34307. var pixel_data;
  34308. var numAlphaBits = header.flags & 0xf;
  34309. var pixel_size = header.pixel_size >> 3;
  34310. var pixel_total = header.width * header.height * pixel_size;
  34311. // Read palettes
  34312. var palettes;
  34313. if (use_pal) {
  34314. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  34315. }
  34316. // Read LRE
  34317. if (use_rle) {
  34318. pixel_data = new Uint8Array(pixel_total);
  34319. var c, count, i;
  34320. var localOffset = 0;
  34321. var pixels = new Uint8Array(pixel_size);
  34322. while (offset < pixel_total && localOffset < pixel_total) {
  34323. c = data[offset++];
  34324. count = (c & 0x7f) + 1;
  34325. // RLE pixels
  34326. if (c & 0x80) {
  34327. // Bind pixel tmp array
  34328. for (i = 0; i < pixel_size; ++i) {
  34329. pixels[i] = data[offset++];
  34330. }
  34331. // Copy pixel array
  34332. for (i = 0; i < count; ++i) {
  34333. pixel_data.set(pixels, localOffset + i * pixel_size);
  34334. }
  34335. localOffset += pixel_size * count;
  34336. }
  34337. else {
  34338. count *= pixel_size;
  34339. for (i = 0; i < count; ++i) {
  34340. pixel_data[localOffset + i] = data[offset++];
  34341. }
  34342. localOffset += count;
  34343. }
  34344. }
  34345. }
  34346. else {
  34347. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  34348. }
  34349. // Load to texture
  34350. var x_start, y_start, x_step, y_step, y_end, x_end;
  34351. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  34352. default:
  34353. case TGATools._ORIGIN_UL:
  34354. x_start = 0;
  34355. x_step = 1;
  34356. x_end = header.width;
  34357. y_start = 0;
  34358. y_step = 1;
  34359. y_end = header.height;
  34360. break;
  34361. case TGATools._ORIGIN_BL:
  34362. x_start = 0;
  34363. x_step = 1;
  34364. x_end = header.width;
  34365. y_start = header.height - 1;
  34366. y_step = -1;
  34367. y_end = -1;
  34368. break;
  34369. case TGATools._ORIGIN_UR:
  34370. x_start = header.width - 1;
  34371. x_step = -1;
  34372. x_end = -1;
  34373. y_start = 0;
  34374. y_step = 1;
  34375. y_end = header.height;
  34376. break;
  34377. case TGATools._ORIGIN_BR:
  34378. x_start = header.width - 1;
  34379. x_step = -1;
  34380. x_end = -1;
  34381. y_start = header.height - 1;
  34382. y_step = -1;
  34383. y_end = -1;
  34384. break;
  34385. }
  34386. // Load the specify method
  34387. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  34388. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  34389. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  34390. };
  34391. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34392. var image = pixel_data, colormap = palettes;
  34393. var width = header.width, height = header.height;
  34394. var color, i = 0, x, y;
  34395. var imageData = new Uint8Array(width * height * 4);
  34396. for (y = y_start; y !== y_end; y += y_step) {
  34397. for (x = x_start; x !== x_end; x += x_step, i++) {
  34398. color = image[i];
  34399. imageData[(x + width * y) * 4 + 3] = 255;
  34400. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  34401. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  34402. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  34403. }
  34404. }
  34405. return imageData;
  34406. };
  34407. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34408. var image = pixel_data;
  34409. var width = header.width, height = header.height;
  34410. var color, i = 0, x, y;
  34411. var imageData = new Uint8Array(width * height * 4);
  34412. for (y = y_start; y !== y_end; y += y_step) {
  34413. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  34414. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  34415. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  34416. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  34417. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  34418. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  34419. }
  34420. }
  34421. return imageData;
  34422. };
  34423. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34424. var image = pixel_data;
  34425. var width = header.width, height = header.height;
  34426. var i = 0, x, y;
  34427. var imageData = new Uint8Array(width * height * 4);
  34428. for (y = y_start; y !== y_end; y += y_step) {
  34429. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  34430. imageData[(x + width * y) * 4 + 3] = 255;
  34431. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34432. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  34433. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  34434. }
  34435. }
  34436. return imageData;
  34437. };
  34438. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34439. var image = pixel_data;
  34440. var width = header.width, height = header.height;
  34441. var i = 0, x, y;
  34442. var imageData = new Uint8Array(width * height * 4);
  34443. for (y = y_start; y !== y_end; y += y_step) {
  34444. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  34445. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34446. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  34447. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  34448. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  34449. }
  34450. }
  34451. return imageData;
  34452. };
  34453. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34454. var image = pixel_data;
  34455. var width = header.width, height = header.height;
  34456. var color, i = 0, x, y;
  34457. var imageData = new Uint8Array(width * height * 4);
  34458. for (y = y_start; y !== y_end; y += y_step) {
  34459. for (x = x_start; x !== x_end; x += x_step, i++) {
  34460. color = image[i];
  34461. imageData[(x + width * y) * 4 + 0] = color;
  34462. imageData[(x + width * y) * 4 + 1] = color;
  34463. imageData[(x + width * y) * 4 + 2] = color;
  34464. imageData[(x + width * y) * 4 + 3] = 255;
  34465. }
  34466. }
  34467. return imageData;
  34468. };
  34469. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  34470. var image = pixel_data;
  34471. var width = header.width, height = header.height;
  34472. var i = 0, x, y;
  34473. var imageData = new Uint8Array(width * height * 4);
  34474. for (y = y_start; y !== y_end; y += y_step) {
  34475. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  34476. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  34477. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  34478. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  34479. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  34480. }
  34481. }
  34482. return imageData;
  34483. };
  34484. TGATools._TYPE_NO_DATA = 0;
  34485. TGATools._TYPE_INDEXED = 1;
  34486. TGATools._TYPE_RGB = 2;
  34487. TGATools._TYPE_GREY = 3;
  34488. TGATools._TYPE_RLE_INDEXED = 9;
  34489. TGATools._TYPE_RLE_RGB = 10;
  34490. TGATools._TYPE_RLE_GREY = 11;
  34491. TGATools._ORIGIN_MASK = 0x30;
  34492. TGATools._ORIGIN_SHIFT = 0x04;
  34493. TGATools._ORIGIN_BL = 0x00;
  34494. TGATools._ORIGIN_BR = 0x01;
  34495. TGATools._ORIGIN_UL = 0x02;
  34496. TGATools._ORIGIN_UR = 0x03;
  34497. return TGATools;
  34498. }());
  34499. Internals.TGATools = TGATools;
  34500. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34501. })(BABYLON || (BABYLON = {}));
  34502. //# sourceMappingURL=babylon.tga.js.map
  34503. var BABYLON;
  34504. (function (BABYLON) {
  34505. var Internals;
  34506. (function (Internals) {
  34507. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  34508. // All values and structures referenced from:
  34509. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  34510. var DDS_MAGIC = 0x20534444;
  34511. 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;
  34512. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  34513. 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;
  34514. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  34515. function FourCCToInt32(value) {
  34516. return value.charCodeAt(0) +
  34517. (value.charCodeAt(1) << 8) +
  34518. (value.charCodeAt(2) << 16) +
  34519. (value.charCodeAt(3) << 24);
  34520. }
  34521. function Int32ToFourCC(value) {
  34522. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  34523. }
  34524. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  34525. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  34526. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  34527. var FOURCC_DX10 = FourCCToInt32("DX10");
  34528. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  34529. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  34530. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  34531. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  34532. var headerLengthInt = 31; // The header length in 32 bit ints
  34533. // Offsets into the header array
  34534. var off_magic = 0;
  34535. var off_size = 1;
  34536. var off_flags = 2;
  34537. var off_height = 3;
  34538. var off_width = 4;
  34539. var off_mipmapCount = 7;
  34540. var off_pfFlags = 20;
  34541. var off_pfFourCC = 21;
  34542. var off_RGBbpp = 22;
  34543. var off_RMask = 23;
  34544. var off_GMask = 24;
  34545. var off_BMask = 25;
  34546. var off_AMask = 26;
  34547. var off_caps1 = 27;
  34548. var off_caps2 = 28;
  34549. var off_caps3 = 29;
  34550. var off_caps4 = 30;
  34551. var off_dxgiFormat = 32;
  34552. ;
  34553. var DDSTools = (function () {
  34554. function DDSTools() {
  34555. }
  34556. DDSTools.GetDDSInfo = function (arrayBuffer) {
  34557. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  34558. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  34559. var mipmapCount = 1;
  34560. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  34561. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34562. }
  34563. var fourCC = header[off_pfFourCC];
  34564. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  34565. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34566. switch (fourCC) {
  34567. case FOURCC_D3DFMT_R16G16B16A16F:
  34568. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  34569. break;
  34570. case FOURCC_D3DFMT_R32G32B32A32F:
  34571. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34572. break;
  34573. case FOURCC_DX10:
  34574. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  34575. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  34576. break;
  34577. }
  34578. }
  34579. return {
  34580. width: header[off_width],
  34581. height: header[off_height],
  34582. mipmapCount: mipmapCount,
  34583. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  34584. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  34585. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  34586. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  34587. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  34588. dxgiFormat: dxgiFormat,
  34589. textureType: textureType
  34590. };
  34591. };
  34592. DDSTools._ToHalfFloat = function (value) {
  34593. if (!DDSTools._FloatView) {
  34594. DDSTools._FloatView = new Float32Array(1);
  34595. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  34596. }
  34597. DDSTools._FloatView[0] = value;
  34598. var x = DDSTools._Int32View[0];
  34599. var bits = (x >> 16) & 0x8000; /* Get the sign */
  34600. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  34601. var e = (x >> 23) & 0xff; /* Using int is faster here */
  34602. /* If zero, or denormal, or exponent underflows too much for a denormal
  34603. * half, return signed zero. */
  34604. if (e < 103) {
  34605. return bits;
  34606. }
  34607. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  34608. if (e > 142) {
  34609. bits |= 0x7c00;
  34610. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  34611. * not Inf, so make sure we set one mantissa bit too. */
  34612. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  34613. return bits;
  34614. }
  34615. /* If exponent underflows but not too much, return a denormal */
  34616. if (e < 113) {
  34617. m |= 0x0800;
  34618. /* Extra rounding may overflow and set mantissa to 0 and exponent
  34619. * to 1, which is OK. */
  34620. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  34621. return bits;
  34622. }
  34623. bits |= ((e - 112) << 10) | (m >> 1);
  34624. bits += m & 1;
  34625. return bits;
  34626. };
  34627. DDSTools._FromHalfFloat = function (value) {
  34628. var s = (value & 0x8000) >> 15;
  34629. var e = (value & 0x7C00) >> 10;
  34630. var f = value & 0x03FF;
  34631. if (e === 0) {
  34632. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  34633. }
  34634. else if (e == 0x1F) {
  34635. return f ? NaN : ((s ? -1 : 1) * Infinity);
  34636. }
  34637. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  34638. };
  34639. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34640. var destArray = new Float32Array(dataLength);
  34641. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34642. var index = 0;
  34643. for (var y = 0; y < height; y++) {
  34644. for (var x = 0; x < width; x++) {
  34645. var srcPos = (x + y * width) * 4;
  34646. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  34647. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  34648. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  34649. if (DDSTools.StoreLODInAlphaChannel) {
  34650. destArray[index + 3] = lod;
  34651. }
  34652. else {
  34653. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  34654. }
  34655. index += 4;
  34656. }
  34657. }
  34658. return destArray;
  34659. };
  34660. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34661. if (DDSTools.StoreLODInAlphaChannel) {
  34662. var destArray = new Uint16Array(dataLength);
  34663. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34664. var index = 0;
  34665. for (var y = 0; y < height; y++) {
  34666. for (var x = 0; x < width; x++) {
  34667. var srcPos = (x + y * width) * 4;
  34668. destArray[index] = srcData[srcPos];
  34669. destArray[index + 1] = srcData[srcPos + 1];
  34670. destArray[index + 2] = srcData[srcPos + 2];
  34671. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  34672. index += 4;
  34673. }
  34674. }
  34675. return destArray;
  34676. }
  34677. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  34678. };
  34679. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34680. if (DDSTools.StoreLODInAlphaChannel) {
  34681. var destArray = new Float32Array(dataLength);
  34682. var srcData = new Float32Array(arrayBuffer, dataOffset);
  34683. var index = 0;
  34684. for (var y = 0; y < height; y++) {
  34685. for (var x = 0; x < width; x++) {
  34686. var srcPos = (x + y * width) * 4;
  34687. destArray[index] = srcData[srcPos];
  34688. destArray[index + 1] = srcData[srcPos + 1];
  34689. destArray[index + 2] = srcData[srcPos + 2];
  34690. destArray[index + 3] = lod;
  34691. index += 4;
  34692. }
  34693. }
  34694. return destArray;
  34695. }
  34696. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  34697. };
  34698. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34699. var destArray = new Uint8Array(dataLength);
  34700. var srcData = new Float32Array(arrayBuffer, dataOffset);
  34701. var index = 0;
  34702. for (var y = 0; y < height; y++) {
  34703. for (var x = 0; x < width; x++) {
  34704. var srcPos = (x + y * width) * 4;
  34705. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  34706. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  34707. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  34708. if (DDSTools.StoreLODInAlphaChannel) {
  34709. destArray[index + 3] = lod;
  34710. }
  34711. else {
  34712. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  34713. }
  34714. index += 4;
  34715. }
  34716. }
  34717. return destArray;
  34718. };
  34719. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  34720. var destArray = new Uint8Array(dataLength);
  34721. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  34722. var index = 0;
  34723. for (var y = 0; y < height; y++) {
  34724. for (var x = 0; x < width; x++) {
  34725. var srcPos = (x + y * width) * 4;
  34726. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  34727. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  34728. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  34729. if (DDSTools.StoreLODInAlphaChannel) {
  34730. destArray[index + 3] = lod;
  34731. }
  34732. else {
  34733. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  34734. }
  34735. index += 4;
  34736. }
  34737. }
  34738. return destArray;
  34739. };
  34740. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34741. var byteArray = new Uint8Array(dataLength);
  34742. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34743. var index = 0;
  34744. for (var y = 0; y < height; y++) {
  34745. for (var x = 0; x < width; x++) {
  34746. var srcPos = (x + y * width) * 4;
  34747. byteArray[index] = srcData[srcPos + 2];
  34748. byteArray[index + 1] = srcData[srcPos + 1];
  34749. byteArray[index + 2] = srcData[srcPos];
  34750. byteArray[index + 3] = srcData[srcPos + 3];
  34751. index += 4;
  34752. }
  34753. }
  34754. return byteArray;
  34755. };
  34756. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34757. var byteArray = new Uint8Array(dataLength);
  34758. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34759. var index = 0;
  34760. for (var y = 0; y < height; y++) {
  34761. for (var x = 0; x < width; x++) {
  34762. var srcPos = (x + y * width) * 3;
  34763. byteArray[index] = srcData[srcPos + 2];
  34764. byteArray[index + 1] = srcData[srcPos + 1];
  34765. byteArray[index + 2] = srcData[srcPos];
  34766. index += 3;
  34767. }
  34768. }
  34769. return byteArray;
  34770. };
  34771. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34772. var byteArray = new Uint8Array(dataLength);
  34773. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  34774. var index = 0;
  34775. for (var y = 0; y < height; y++) {
  34776. for (var x = 0; x < width; x++) {
  34777. var srcPos = (x + y * width);
  34778. byteArray[index] = srcData[srcPos];
  34779. index++;
  34780. }
  34781. }
  34782. return byteArray;
  34783. };
  34784. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  34785. if (lodIndex === void 0) { lodIndex = -1; }
  34786. var ext = engine.getCaps().s3tc;
  34787. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  34788. if (header[off_magic] != DDS_MAGIC) {
  34789. BABYLON.Tools.Error("Invalid magic number in DDS header");
  34790. return;
  34791. }
  34792. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  34793. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  34794. return;
  34795. }
  34796. if (info.isCompressed && !ext) {
  34797. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  34798. return;
  34799. }
  34800. var bpp = header[off_RGBbpp];
  34801. dataOffset = header[off_size] + 4;
  34802. var computeFormats = false;
  34803. if (info.isFourCC) {
  34804. fourCC = header[off_pfFourCC];
  34805. switch (fourCC) {
  34806. case FOURCC_DXT1:
  34807. blockBytes = 8;
  34808. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  34809. break;
  34810. case FOURCC_DXT3:
  34811. blockBytes = 16;
  34812. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  34813. break;
  34814. case FOURCC_DXT5:
  34815. blockBytes = 16;
  34816. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  34817. break;
  34818. case FOURCC_D3DFMT_R16G16B16A16F:
  34819. computeFormats = true;
  34820. break;
  34821. case FOURCC_D3DFMT_R32G32B32A32F:
  34822. computeFormats = true;
  34823. break;
  34824. case FOURCC_DX10:
  34825. // There is an additionnal header so dataOffset need to be changed
  34826. dataOffset += 5 * 4; // 5 uints
  34827. var supported = false;
  34828. switch (info.dxgiFormat) {
  34829. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  34830. computeFormats = true;
  34831. supported = true;
  34832. break;
  34833. case DXGI_FORMAT_B8G8R8X8_UNORM:
  34834. info.isRGB = true;
  34835. info.isFourCC = false;
  34836. bpp = 32;
  34837. supported = true;
  34838. break;
  34839. }
  34840. if (supported) {
  34841. break;
  34842. }
  34843. default:
  34844. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  34845. return;
  34846. }
  34847. }
  34848. if (computeFormats) {
  34849. format = engine._getWebGLTextureType(info.textureType);
  34850. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34851. }
  34852. mipmapCount = 1;
  34853. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  34854. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34855. }
  34856. for (var face = 0; face < faces; face++) {
  34857. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34858. width = header[off_width];
  34859. height = header[off_height];
  34860. for (mip = 0; mip < mipmapCount; ++mip) {
  34861. if (lodIndex === -1 || lodIndex === mip) {
  34862. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  34863. var i = (lodIndex === -1) ? mip : 0;
  34864. if (!info.isCompressed && info.isFourCC) {
  34865. dataLength = width * height * 4;
  34866. var floatArray;
  34867. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  34868. if (bpp === 128) {
  34869. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34870. }
  34871. else if (bpp === 64) {
  34872. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34873. }
  34874. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  34875. format = engine._getWebGLTextureType(info.textureType);
  34876. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34877. }
  34878. else {
  34879. if (bpp === 128) {
  34880. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34881. }
  34882. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  34883. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34884. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  34885. format = engine._getWebGLTextureType(info.textureType);
  34886. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  34887. }
  34888. else {
  34889. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  34890. }
  34891. }
  34892. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  34893. }
  34894. else if (info.isRGB) {
  34895. if (bpp === 24) {
  34896. dataLength = width * height * 3;
  34897. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34898. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  34899. }
  34900. else {
  34901. dataLength = width * height * 4;
  34902. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34903. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  34904. }
  34905. }
  34906. else if (info.isLuminance) {
  34907. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  34908. var unpaddedRowSize = width;
  34909. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  34910. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  34911. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34912. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  34913. }
  34914. else {
  34915. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  34916. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  34917. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  34918. }
  34919. }
  34920. dataOffset += width * height * (bpp / 8);
  34921. width *= 0.5;
  34922. height *= 0.5;
  34923. width = Math.max(1.0, width);
  34924. height = Math.max(1.0, height);
  34925. }
  34926. }
  34927. };
  34928. DDSTools.StoreLODInAlphaChannel = false;
  34929. return DDSTools;
  34930. }());
  34931. Internals.DDSTools = DDSTools;
  34932. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34933. })(BABYLON || (BABYLON = {}));
  34934. //# sourceMappingURL=babylon.dds.js.map
  34935. var BABYLON;
  34936. (function (BABYLON) {
  34937. var Internals;
  34938. (function (Internals) {
  34939. /**
  34940. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  34941. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  34942. */
  34943. var KhronosTextureContainer = (function () {
  34944. /**
  34945. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  34946. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  34947. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  34948. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  34949. */
  34950. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  34951. this.arrayBuffer = arrayBuffer;
  34952. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  34953. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  34954. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  34955. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  34956. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  34957. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  34958. BABYLON.Tools.Error("texture missing KTX identifier");
  34959. return;
  34960. }
  34961. // load the reset of the header in native 32 bit int
  34962. var header = new Int32Array(this.arrayBuffer, 12, 13);
  34963. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  34964. var oppositeEndianess = header[0] === 0x01020304;
  34965. // read all the header elements in order they exist in the file, without modification (sans endainness)
  34966. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  34967. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  34968. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  34969. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  34970. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  34971. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  34972. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  34973. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  34974. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  34975. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  34976. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  34977. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  34978. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  34979. if (this.glType !== 0) {
  34980. BABYLON.Tools.Error("only compressed formats currently supported");
  34981. return;
  34982. }
  34983. else {
  34984. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  34985. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  34986. }
  34987. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  34988. BABYLON.Tools.Error("only 2D textures currently supported");
  34989. return;
  34990. }
  34991. if (this.numberOfArrayElements !== 0) {
  34992. BABYLON.Tools.Error("texture arrays not currently supported");
  34993. return;
  34994. }
  34995. if (this.numberOfFaces !== facesExpected) {
  34996. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  34997. return;
  34998. }
  34999. // we now have a completely validated file, so could use existence of loadType as success
  35000. // would need to make this more elaborate & adjust checks above to support more than one load type
  35001. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  35002. }
  35003. // not as fast hardware based, but will probably never need to use
  35004. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  35005. return ((val & 0xFF) << 24)
  35006. | ((val & 0xFF00) << 8)
  35007. | ((val >> 8) & 0xFF00)
  35008. | ((val >> 24) & 0xFF);
  35009. };
  35010. /**
  35011. * It is assumed that the texture has already been created & is currently bound
  35012. */
  35013. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  35014. switch (this.loadType) {
  35015. case KhronosTextureContainer.COMPRESSED_2D:
  35016. this._upload2DCompressedLevels(gl, loadMipmaps);
  35017. break;
  35018. case KhronosTextureContainer.TEX_2D:
  35019. case KhronosTextureContainer.COMPRESSED_3D:
  35020. case KhronosTextureContainer.TEX_3D:
  35021. }
  35022. };
  35023. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  35024. // initialize width & height for level 1
  35025. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  35026. var width = this.pixelWidth;
  35027. var height = this.pixelHeight;
  35028. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  35029. for (var level = 0; level < mipmapCount; level++) {
  35030. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  35031. for (var face = 0; face < this.numberOfFaces; face++) {
  35032. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  35033. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  35034. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  35035. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  35036. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  35037. }
  35038. width = Math.max(1.0, width * 0.5);
  35039. height = Math.max(1.0, height * 0.5);
  35040. }
  35041. };
  35042. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  35043. // load types
  35044. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  35045. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  35046. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  35047. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  35048. return KhronosTextureContainer;
  35049. }());
  35050. Internals.KhronosTextureContainer = KhronosTextureContainer;
  35051. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35052. })(BABYLON || (BABYLON = {}));
  35053. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  35054. var BABYLON;
  35055. (function (BABYLON) {
  35056. var PostProcess = (function () {
  35057. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  35058. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  35059. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35060. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  35061. if (blockCompilation === void 0) { blockCompilation = false; }
  35062. this.name = name;
  35063. this.width = -1;
  35064. this.height = -1;
  35065. this.autoClear = true;
  35066. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  35067. /*
  35068. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  35069. Can only be used on a single postprocess or on the last one of a chain.
  35070. */
  35071. this.enablePixelPerfectMode = false;
  35072. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  35073. this.alwaysForcePOT = false;
  35074. this.samples = 1;
  35075. this._reusable = false;
  35076. this._textures = new BABYLON.SmartArray(2);
  35077. this._currentRenderTextureInd = 0;
  35078. this._scaleRatio = new BABYLON.Vector2(1, 1);
  35079. this._texelSize = BABYLON.Vector2.Zero();
  35080. // Events
  35081. /**
  35082. * An event triggered when the postprocess is activated.
  35083. * @type {BABYLON.Observable}
  35084. */
  35085. this.onActivateObservable = new BABYLON.Observable();
  35086. /**
  35087. * An event triggered when the postprocess changes its size.
  35088. * @type {BABYLON.Observable}
  35089. */
  35090. this.onSizeChangedObservable = new BABYLON.Observable();
  35091. /**
  35092. * An event triggered when the postprocess applies its effect.
  35093. * @type {BABYLON.Observable}
  35094. */
  35095. this.onApplyObservable = new BABYLON.Observable();
  35096. /**
  35097. * An event triggered before rendering the postprocess
  35098. * @type {BABYLON.Observable}
  35099. */
  35100. this.onBeforeRenderObservable = new BABYLON.Observable();
  35101. /**
  35102. * An event triggered after rendering the postprocess
  35103. * @type {BABYLON.Observable}
  35104. */
  35105. this.onAfterRenderObservable = new BABYLON.Observable();
  35106. if (camera != null) {
  35107. this._camera = camera;
  35108. this._scene = camera.getScene();
  35109. camera.attachPostProcess(this);
  35110. this._engine = this._scene.getEngine();
  35111. this._scene.postProcesses.push(this);
  35112. }
  35113. else {
  35114. this._engine = engine;
  35115. this._engine.postProcesses.push(this);
  35116. }
  35117. this._options = options;
  35118. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  35119. this._reusable = reusable || false;
  35120. this._textureType = textureType;
  35121. this._samplers = samplers || [];
  35122. this._samplers.push("textureSampler");
  35123. this._fragmentUrl = fragmentUrl;
  35124. this._vertexUrl = vertexUrl;
  35125. this._parameters = parameters || [];
  35126. this._parameters.push("scale");
  35127. this._indexParameters = indexParameters;
  35128. if (!blockCompilation) {
  35129. this.updateEffect(defines);
  35130. }
  35131. }
  35132. Object.defineProperty(PostProcess.prototype, "onActivate", {
  35133. set: function (callback) {
  35134. if (this._onActivateObserver) {
  35135. this.onActivateObservable.remove(this._onActivateObserver);
  35136. }
  35137. this._onActivateObserver = this.onActivateObservable.add(callback);
  35138. },
  35139. enumerable: true,
  35140. configurable: true
  35141. });
  35142. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  35143. set: function (callback) {
  35144. if (this._onSizeChangedObserver) {
  35145. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  35146. }
  35147. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  35148. },
  35149. enumerable: true,
  35150. configurable: true
  35151. });
  35152. Object.defineProperty(PostProcess.prototype, "onApply", {
  35153. set: function (callback) {
  35154. if (this._onApplyObserver) {
  35155. this.onApplyObservable.remove(this._onApplyObserver);
  35156. }
  35157. this._onApplyObserver = this.onApplyObservable.add(callback);
  35158. },
  35159. enumerable: true,
  35160. configurable: true
  35161. });
  35162. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  35163. set: function (callback) {
  35164. if (this._onBeforeRenderObserver) {
  35165. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  35166. }
  35167. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  35168. },
  35169. enumerable: true,
  35170. configurable: true
  35171. });
  35172. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  35173. set: function (callback) {
  35174. if (this._onAfterRenderObserver) {
  35175. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  35176. }
  35177. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  35178. },
  35179. enumerable: true,
  35180. configurable: true
  35181. });
  35182. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  35183. get: function () {
  35184. return this._textures.data[this._currentRenderTextureInd];
  35185. },
  35186. set: function (value) {
  35187. this._forcedOutputTexture = value;
  35188. },
  35189. enumerable: true,
  35190. configurable: true
  35191. });
  35192. PostProcess.prototype.getCamera = function () {
  35193. return this._camera;
  35194. };
  35195. Object.defineProperty(PostProcess.prototype, "texelSize", {
  35196. get: function () {
  35197. if (this._shareOutputWithPostProcess) {
  35198. return this._shareOutputWithPostProcess.texelSize;
  35199. }
  35200. if (this._forcedOutputTexture) {
  35201. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  35202. }
  35203. return this._texelSize;
  35204. },
  35205. enumerable: true,
  35206. configurable: true
  35207. });
  35208. PostProcess.prototype.getEngine = function () {
  35209. return this._engine;
  35210. };
  35211. PostProcess.prototype.getEffect = function () {
  35212. return this._effect;
  35213. };
  35214. PostProcess.prototype.shareOutputWith = function (postProcess) {
  35215. this._disposeTextures();
  35216. this._shareOutputWithPostProcess = postProcess;
  35217. return this;
  35218. };
  35219. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  35220. 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);
  35221. };
  35222. PostProcess.prototype.isReusable = function () {
  35223. return this._reusable;
  35224. };
  35225. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  35226. PostProcess.prototype.markTextureDirty = function () {
  35227. this.width = -1;
  35228. };
  35229. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  35230. var _this = this;
  35231. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  35232. camera = camera || this._camera;
  35233. var scene = camera.getScene();
  35234. var engine = scene.getEngine();
  35235. var maxSize = engine.getCaps().maxTextureSize;
  35236. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  35237. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  35238. var desiredWidth = this._options.width || requiredWidth;
  35239. var desiredHeight = this._options.height || requiredHeight;
  35240. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  35241. if (!this._options.width) {
  35242. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  35243. }
  35244. if (!this._options.height) {
  35245. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  35246. }
  35247. }
  35248. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  35249. if (this._textures.length > 0) {
  35250. for (var i = 0; i < this._textures.length; i++) {
  35251. this._engine._releaseTexture(this._textures.data[i]);
  35252. }
  35253. this._textures.reset();
  35254. }
  35255. this.width = desiredWidth;
  35256. this.height = desiredHeight;
  35257. var textureSize = { width: this.width, height: this.height };
  35258. var textureOptions = {
  35259. generateMipMaps: false,
  35260. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  35261. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  35262. samplingMode: this.renderTargetSamplingMode,
  35263. type: this._textureType
  35264. };
  35265. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35266. if (this._reusable) {
  35267. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35268. }
  35269. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  35270. this.onSizeChangedObservable.notifyObservers(this);
  35271. }
  35272. this._textures.forEach(function (texture) {
  35273. if (texture.samples !== _this.samples) {
  35274. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  35275. }
  35276. });
  35277. }
  35278. var target;
  35279. if (this._shareOutputWithPostProcess) {
  35280. target = this._shareOutputWithPostProcess.outputTexture;
  35281. }
  35282. else if (this._forcedOutputTexture) {
  35283. target = this._forcedOutputTexture;
  35284. this.width = this._forcedOutputTexture.width;
  35285. this.height = this._forcedOutputTexture.height;
  35286. }
  35287. else {
  35288. target = this.outputTexture;
  35289. }
  35290. if (this.enablePixelPerfectMode) {
  35291. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  35292. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  35293. }
  35294. else {
  35295. this._scaleRatio.copyFromFloats(1, 1);
  35296. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  35297. }
  35298. this.onActivateObservable.notifyObservers(camera);
  35299. // Clear
  35300. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  35301. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  35302. }
  35303. if (this._reusable) {
  35304. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  35305. }
  35306. };
  35307. Object.defineProperty(PostProcess.prototype, "isSupported", {
  35308. get: function () {
  35309. return this._effect.isSupported;
  35310. },
  35311. enumerable: true,
  35312. configurable: true
  35313. });
  35314. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  35315. get: function () {
  35316. if (this._shareOutputWithPostProcess) {
  35317. return this._shareOutputWithPostProcess.aspectRatio;
  35318. }
  35319. if (this._forcedOutputTexture) {
  35320. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  35321. }
  35322. return this.width / this.height;
  35323. },
  35324. enumerable: true,
  35325. configurable: true
  35326. });
  35327. PostProcess.prototype.apply = function () {
  35328. // Check
  35329. if (!this._effect || !this._effect.isReady())
  35330. return null;
  35331. // States
  35332. this._engine.enableEffect(this._effect);
  35333. this._engine.setState(false);
  35334. this._engine.setDepthBuffer(false);
  35335. this._engine.setDepthWrite(false);
  35336. // Alpha
  35337. this._engine.setAlphaMode(this.alphaMode);
  35338. if (this.alphaConstants) {
  35339. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  35340. }
  35341. // Texture
  35342. var source;
  35343. if (this._shareOutputWithPostProcess) {
  35344. source = this._shareOutputWithPostProcess.outputTexture;
  35345. }
  35346. else if (this._forcedOutputTexture) {
  35347. source = this._forcedOutputTexture;
  35348. }
  35349. else {
  35350. source = this.outputTexture;
  35351. }
  35352. this._effect._bindTexture("textureSampler", source);
  35353. // Parameters
  35354. this._effect.setVector2("scale", this._scaleRatio);
  35355. this.onApplyObservable.notifyObservers(this._effect);
  35356. return this._effect;
  35357. };
  35358. PostProcess.prototype._disposeTextures = function () {
  35359. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  35360. return;
  35361. }
  35362. if (this._textures.length > 0) {
  35363. for (var i = 0; i < this._textures.length; i++) {
  35364. this._engine._releaseTexture(this._textures.data[i]);
  35365. }
  35366. }
  35367. this._textures.dispose();
  35368. };
  35369. PostProcess.prototype.dispose = function (camera) {
  35370. camera = camera || this._camera;
  35371. this._disposeTextures();
  35372. if (this._scene) {
  35373. var index_1 = this._scene.postProcesses.indexOf(this);
  35374. if (index_1 !== -1) {
  35375. this._scene.postProcesses.splice(index_1, 1);
  35376. }
  35377. }
  35378. else {
  35379. var index_2 = this._engine.postProcesses.indexOf(this);
  35380. if (index_2 !== -1) {
  35381. this._engine.postProcesses.splice(index_2, 1);
  35382. }
  35383. }
  35384. if (!camera) {
  35385. return;
  35386. }
  35387. camera.detachPostProcess(this);
  35388. var index = camera._postProcesses.indexOf(this);
  35389. if (index === 0 && camera._postProcesses.length > 0) {
  35390. this._camera._postProcesses[0].markTextureDirty();
  35391. }
  35392. this.onActivateObservable.clear();
  35393. this.onAfterRenderObservable.clear();
  35394. this.onApplyObservable.clear();
  35395. this.onBeforeRenderObservable.clear();
  35396. this.onSizeChangedObservable.clear();
  35397. };
  35398. return PostProcess;
  35399. }());
  35400. BABYLON.PostProcess = PostProcess;
  35401. })(BABYLON || (BABYLON = {}));
  35402. //# sourceMappingURL=babylon.postProcess.js.map
  35403. var BABYLON;
  35404. (function (BABYLON) {
  35405. var PassPostProcess = (function (_super) {
  35406. __extends(PassPostProcess, _super);
  35407. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  35408. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35409. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  35410. }
  35411. return PassPostProcess;
  35412. }(BABYLON.PostProcess));
  35413. BABYLON.PassPostProcess = PassPostProcess;
  35414. })(BABYLON || (BABYLON = {}));
  35415. //# sourceMappingURL=babylon.passPostProcess.js.map
  35416. var BABYLON;
  35417. (function (BABYLON) {
  35418. var ShadowGenerator = (function () {
  35419. /**
  35420. * Creates a ShadowGenerator object.
  35421. * A ShadowGenerator is the required tool to use the shadows.
  35422. * Each light casting shadows needs to use its own ShadowGenerator.
  35423. * Required parameters :
  35424. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  35425. * - `light`: the light object generating the shadows.
  35426. * - `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.
  35427. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  35428. */
  35429. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  35430. // Members
  35431. this._bias = 0.00005;
  35432. this._blurBoxOffset = 1;
  35433. this._blurScale = 2;
  35434. this._blurKernel = 1;
  35435. this._useKernelBlur = false;
  35436. this._filter = ShadowGenerator.FILTER_NONE;
  35437. this._darkness = 0;
  35438. this._transparencyShadow = false;
  35439. /**
  35440. * Controls the extent to which the shadows fade out at the edge of the frustum
  35441. * Used only by directionals and spots
  35442. */
  35443. this.frustumEdgeFalloff = 0;
  35444. this.forceBackFacesOnly = false;
  35445. this._lightDirection = BABYLON.Vector3.Zero();
  35446. this._viewMatrix = BABYLON.Matrix.Zero();
  35447. this._projectionMatrix = BABYLON.Matrix.Zero();
  35448. this._transformMatrix = BABYLON.Matrix.Zero();
  35449. this._worldViewProjection = BABYLON.Matrix.Zero();
  35450. this._currentFaceIndex = 0;
  35451. this._currentFaceIndexCache = 0;
  35452. this._isCube = false;
  35453. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  35454. this._mapSize = mapSize;
  35455. this._light = light;
  35456. this._scene = light.getScene();
  35457. light._shadowGenerator = this;
  35458. // Texture type fallback from float to int if not supported.
  35459. var caps = this._scene.getEngine().getCaps();
  35460. if (!useFullFloatFirst) {
  35461. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  35462. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  35463. }
  35464. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  35465. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  35466. }
  35467. else {
  35468. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  35469. }
  35470. }
  35471. else {
  35472. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  35473. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  35474. }
  35475. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  35476. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  35477. }
  35478. else {
  35479. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  35480. }
  35481. }
  35482. this._initializeGenerator();
  35483. }
  35484. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  35485. // Static
  35486. get: function () {
  35487. return ShadowGenerator._FILTER_NONE;
  35488. },
  35489. enumerable: true,
  35490. configurable: true
  35491. });
  35492. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  35493. get: function () {
  35494. return ShadowGenerator._FILTER_POISSONSAMPLING;
  35495. },
  35496. enumerable: true,
  35497. configurable: true
  35498. });
  35499. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  35500. get: function () {
  35501. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  35502. },
  35503. enumerable: true,
  35504. configurable: true
  35505. });
  35506. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  35507. get: function () {
  35508. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  35509. },
  35510. enumerable: true,
  35511. configurable: true
  35512. });
  35513. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  35514. get: function () {
  35515. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  35516. },
  35517. enumerable: true,
  35518. configurable: true
  35519. });
  35520. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  35521. get: function () {
  35522. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  35523. },
  35524. enumerable: true,
  35525. configurable: true
  35526. });
  35527. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  35528. get: function () {
  35529. return this._bias;
  35530. },
  35531. set: function (bias) {
  35532. this._bias = bias;
  35533. },
  35534. enumerable: true,
  35535. configurable: true
  35536. });
  35537. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  35538. get: function () {
  35539. return this._blurBoxOffset;
  35540. },
  35541. set: function (value) {
  35542. if (this._blurBoxOffset === value) {
  35543. return;
  35544. }
  35545. this._blurBoxOffset = value;
  35546. this._disposeBlurPostProcesses();
  35547. },
  35548. enumerable: true,
  35549. configurable: true
  35550. });
  35551. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  35552. get: function () {
  35553. return this._blurScale;
  35554. },
  35555. set: function (value) {
  35556. if (this._blurScale === value) {
  35557. return;
  35558. }
  35559. this._blurScale = value;
  35560. this._disposeBlurPostProcesses();
  35561. },
  35562. enumerable: true,
  35563. configurable: true
  35564. });
  35565. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  35566. get: function () {
  35567. return this._blurKernel;
  35568. },
  35569. set: function (value) {
  35570. if (this._blurKernel === value) {
  35571. return;
  35572. }
  35573. this._blurKernel = value;
  35574. this._disposeBlurPostProcesses();
  35575. },
  35576. enumerable: true,
  35577. configurable: true
  35578. });
  35579. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  35580. get: function () {
  35581. return this._useKernelBlur;
  35582. },
  35583. set: function (value) {
  35584. if (this._useKernelBlur === value) {
  35585. return;
  35586. }
  35587. this._useKernelBlur = value;
  35588. this._disposeBlurPostProcesses();
  35589. },
  35590. enumerable: true,
  35591. configurable: true
  35592. });
  35593. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  35594. get: function () {
  35595. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  35596. },
  35597. set: function (value) {
  35598. this._depthScale = value;
  35599. },
  35600. enumerable: true,
  35601. configurable: true
  35602. });
  35603. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  35604. get: function () {
  35605. return this._filter;
  35606. },
  35607. set: function (value) {
  35608. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  35609. if (this._light.needCube()) {
  35610. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  35611. this.useExponentialShadowMap = true;
  35612. return;
  35613. }
  35614. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  35615. this.useCloseExponentialShadowMap = true;
  35616. return;
  35617. }
  35618. }
  35619. if (this._filter === value) {
  35620. return;
  35621. }
  35622. this._filter = value;
  35623. this._disposeBlurPostProcesses();
  35624. this._applyFilterValues();
  35625. this._light._markMeshesAsLightDirty();
  35626. },
  35627. enumerable: true,
  35628. configurable: true
  35629. });
  35630. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  35631. get: function () {
  35632. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  35633. },
  35634. set: function (value) {
  35635. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  35636. return;
  35637. }
  35638. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  35639. },
  35640. enumerable: true,
  35641. configurable: true
  35642. });
  35643. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  35644. get: function () {
  35645. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  35646. return this.useExponentialShadowMap;
  35647. },
  35648. set: function (value) {
  35649. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  35650. this.useExponentialShadowMap = value;
  35651. },
  35652. enumerable: true,
  35653. configurable: true
  35654. });
  35655. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  35656. get: function () {
  35657. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  35658. return this.useBlurExponentialShadowMap;
  35659. },
  35660. set: function (value) {
  35661. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  35662. this.useBlurExponentialShadowMap = value;
  35663. },
  35664. enumerable: true,
  35665. configurable: true
  35666. });
  35667. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  35668. get: function () {
  35669. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  35670. },
  35671. set: function (value) {
  35672. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  35673. return;
  35674. }
  35675. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35676. },
  35677. enumerable: true,
  35678. configurable: true
  35679. });
  35680. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  35681. get: function () {
  35682. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  35683. },
  35684. set: function (value) {
  35685. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  35686. return;
  35687. }
  35688. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35689. },
  35690. enumerable: true,
  35691. configurable: true
  35692. });
  35693. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  35694. get: function () {
  35695. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  35696. },
  35697. set: function (value) {
  35698. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  35699. return;
  35700. }
  35701. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35702. },
  35703. enumerable: true,
  35704. configurable: true
  35705. });
  35706. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  35707. get: function () {
  35708. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  35709. },
  35710. set: function (value) {
  35711. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  35712. return;
  35713. }
  35714. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  35715. },
  35716. enumerable: true,
  35717. configurable: true
  35718. });
  35719. /**
  35720. * Returns the darkness value (float).
  35721. */
  35722. ShadowGenerator.prototype.getDarkness = function () {
  35723. return this._darkness;
  35724. };
  35725. /**
  35726. * Sets the ShadowGenerator darkness value (float <= 1.0).
  35727. * Returns the ShadowGenerator.
  35728. */
  35729. ShadowGenerator.prototype.setDarkness = function (darkness) {
  35730. if (darkness >= 1.0)
  35731. this._darkness = 1.0;
  35732. else if (darkness <= 0.0)
  35733. this._darkness = 0.0;
  35734. else
  35735. this._darkness = darkness;
  35736. return this;
  35737. };
  35738. /**
  35739. * Sets the ability to have transparent shadow (boolean).
  35740. * Returns the ShadowGenerator.
  35741. */
  35742. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  35743. this._transparencyShadow = hasShadow;
  35744. return this;
  35745. };
  35746. /**
  35747. * Returns a RenderTargetTexture object : the shadow map texture.
  35748. */
  35749. ShadowGenerator.prototype.getShadowMap = function () {
  35750. return this._shadowMap;
  35751. };
  35752. /**
  35753. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  35754. */
  35755. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  35756. if (this._shadowMap2) {
  35757. return this._shadowMap2;
  35758. }
  35759. return this._shadowMap;
  35760. };
  35761. /**
  35762. * Returns the associated light object.
  35763. */
  35764. ShadowGenerator.prototype.getLight = function () {
  35765. return this._light;
  35766. };
  35767. ShadowGenerator.prototype._initializeGenerator = function () {
  35768. this._light._markMeshesAsLightDirty();
  35769. this._initializeShadowMap();
  35770. };
  35771. ShadowGenerator.prototype._initializeShadowMap = function () {
  35772. var _this = this;
  35773. // Render target
  35774. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  35775. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35776. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35777. this._shadowMap.anisotropicFilteringLevel = 1;
  35778. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35779. this._shadowMap.renderParticles = false;
  35780. // Record Face Index before render.
  35781. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  35782. _this._currentFaceIndex = faceIndex;
  35783. });
  35784. // Custom render function.
  35785. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  35786. // Blur if required afer render.
  35787. this._shadowMap.onAfterUnbindObservable.add(function () {
  35788. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  35789. return;
  35790. }
  35791. if (!_this._blurPostProcesses) {
  35792. _this._initializeBlurRTTAndPostProcesses();
  35793. }
  35794. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  35795. });
  35796. // Clear according to the chosen filter.
  35797. this._shadowMap.onClearObservable.add(function (engine) {
  35798. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  35799. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  35800. }
  35801. else {
  35802. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  35803. }
  35804. });
  35805. };
  35806. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  35807. var _this = this;
  35808. var engine = this._scene.getEngine();
  35809. var targetSize = this._mapSize / this.blurScale;
  35810. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  35811. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  35812. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35813. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35814. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35815. }
  35816. if (this.useKernelBlur) {
  35817. 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);
  35818. this._kernelBlurXPostprocess.width = targetSize;
  35819. this._kernelBlurXPostprocess.height = targetSize;
  35820. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  35821. effect.setTexture("textureSampler", _this._shadowMap);
  35822. });
  35823. 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);
  35824. this._kernelBlurXPostprocess.autoClear = false;
  35825. this._kernelBlurYPostprocess.autoClear = false;
  35826. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  35827. this._kernelBlurXPostprocess.packedFloat = true;
  35828. this._kernelBlurYPostprocess.packedFloat = true;
  35829. }
  35830. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  35831. }
  35832. else {
  35833. 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);
  35834. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  35835. effect.setFloat2("screenSize", targetSize, targetSize);
  35836. effect.setTexture("textureSampler", _this._shadowMap);
  35837. });
  35838. this._boxBlurPostprocess.autoClear = false;
  35839. this._blurPostProcesses = [this._boxBlurPostprocess];
  35840. }
  35841. };
  35842. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35843. var index;
  35844. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35845. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  35846. }
  35847. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35848. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  35849. }
  35850. if (this._transparencyShadow) {
  35851. for (index = 0; index < transparentSubMeshes.length; index++) {
  35852. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  35853. }
  35854. }
  35855. };
  35856. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  35857. var _this = this;
  35858. var mesh = subMesh.getRenderingMesh();
  35859. var scene = this._scene;
  35860. var engine = scene.getEngine();
  35861. // Culling
  35862. engine.setState(subMesh.getMaterial().backFaceCulling);
  35863. // Managing instances
  35864. var batch = mesh._getInstancesRenderList(subMesh._id);
  35865. if (batch.mustReturn) {
  35866. return;
  35867. }
  35868. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  35869. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  35870. engine.enableEffect(this._effect);
  35871. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  35872. var material = subMesh.getMaterial();
  35873. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  35874. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  35875. this._effect.setVector3("lightPosition", this.getLight().position);
  35876. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  35877. // Alpha test
  35878. if (material && material.needAlphaTesting()) {
  35879. var alphaTexture = material.getAlphaTestTexture();
  35880. if (alphaTexture) {
  35881. this._effect.setTexture("diffuseSampler", alphaTexture);
  35882. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  35883. }
  35884. }
  35885. // Bones
  35886. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35887. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35888. }
  35889. if (this.forceBackFacesOnly) {
  35890. engine.setState(true, 0, false, true);
  35891. }
  35892. // Draw
  35893. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35894. if (this.forceBackFacesOnly) {
  35895. engine.setState(true, 0, false, false);
  35896. }
  35897. }
  35898. else {
  35899. // Need to reset refresh rate of the shadowMap
  35900. this._shadowMap.resetRefreshCounter();
  35901. }
  35902. };
  35903. ShadowGenerator.prototype._applyFilterValues = function () {
  35904. if (this.filter === ShadowGenerator.FILTER_NONE) {
  35905. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  35906. }
  35907. else {
  35908. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35909. }
  35910. };
  35911. /**
  35912. * Force shader compilation including textures ready check
  35913. */
  35914. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  35915. var _this = this;
  35916. var scene = this._scene;
  35917. var engine = scene.getEngine();
  35918. var subMeshes = new Array();
  35919. var currentIndex = 0;
  35920. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  35921. var mesh = _a[_i];
  35922. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  35923. }
  35924. var checkReady = function () {
  35925. if (!_this._scene || !_this._scene.getEngine()) {
  35926. return;
  35927. }
  35928. var subMesh = subMeshes[currentIndex];
  35929. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  35930. currentIndex++;
  35931. if (currentIndex >= subMeshes.length) {
  35932. if (onCompiled) {
  35933. onCompiled(_this);
  35934. }
  35935. return;
  35936. }
  35937. }
  35938. setTimeout(checkReady, 16);
  35939. };
  35940. if (subMeshes.length > 0) {
  35941. checkReady();
  35942. }
  35943. };
  35944. /**
  35945. * Boolean : true when the ShadowGenerator is finally computed.
  35946. */
  35947. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  35948. var defines = [];
  35949. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  35950. defines.push("#define FLOAT");
  35951. }
  35952. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  35953. defines.push("#define ESM");
  35954. }
  35955. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35956. var mesh = subMesh.getMesh();
  35957. var material = subMesh.getMaterial();
  35958. // Alpha test
  35959. if (material && material.needAlphaTesting()) {
  35960. var alphaTexture = material.getAlphaTestTexture();
  35961. if (alphaTexture) {
  35962. defines.push("#define ALPHATEST");
  35963. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35964. attribs.push(BABYLON.VertexBuffer.UVKind);
  35965. defines.push("#define UV1");
  35966. }
  35967. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35968. if (alphaTexture.coordinatesIndex === 1) {
  35969. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35970. defines.push("#define UV2");
  35971. }
  35972. }
  35973. }
  35974. }
  35975. // Bones
  35976. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35977. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35978. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35979. if (mesh.numBoneInfluencers > 4) {
  35980. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35981. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35982. }
  35983. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35984. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35985. }
  35986. else {
  35987. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35988. }
  35989. // Instances
  35990. if (useInstances) {
  35991. defines.push("#define INSTANCES");
  35992. attribs.push("world0");
  35993. attribs.push("world1");
  35994. attribs.push("world2");
  35995. attribs.push("world3");
  35996. }
  35997. // Get correct effect
  35998. var join = defines.join("\n");
  35999. if (this._cachedDefines !== join) {
  36000. this._cachedDefines = join;
  36001. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  36002. }
  36003. return this._effect.isReady();
  36004. };
  36005. /**
  36006. * This creates the defines related to the standard BJS materials.
  36007. */
  36008. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  36009. var scene = this._scene;
  36010. var light = this._light;
  36011. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  36012. return;
  36013. }
  36014. defines["SHADOW" + lightIndex] = true;
  36015. if (this.usePoissonSampling) {
  36016. defines["SHADOWPCF" + lightIndex] = true;
  36017. }
  36018. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  36019. defines["SHADOWESM" + lightIndex] = true;
  36020. }
  36021. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  36022. defines["SHADOWCLOSEESM" + lightIndex] = true;
  36023. }
  36024. if (light.needCube()) {
  36025. defines["SHADOWCUBE" + lightIndex] = true;
  36026. }
  36027. };
  36028. /**
  36029. * This binds shadow lights related to the standard BJS materials.
  36030. * It implies the unifroms available on the materials are the standard BJS ones.
  36031. */
  36032. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  36033. var light = this._light;
  36034. var scene = this._scene;
  36035. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  36036. return;
  36037. }
  36038. if (!light.needCube()) {
  36039. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  36040. }
  36041. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  36042. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  36043. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  36044. };
  36045. // Methods
  36046. /**
  36047. * Returns a Matrix object : the updated transformation matrix.
  36048. */
  36049. ShadowGenerator.prototype.getTransformMatrix = function () {
  36050. var scene = this._scene;
  36051. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  36052. return this._transformMatrix;
  36053. }
  36054. this._currentRenderID = scene.getRenderId();
  36055. this._currentFaceIndexCache = this._currentFaceIndex;
  36056. var lightPosition = this._light.position;
  36057. if (this._light.computeTransformedInformation()) {
  36058. lightPosition = this._light.transformedPosition;
  36059. }
  36060. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  36061. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  36062. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  36063. }
  36064. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  36065. this._cachedPosition = lightPosition.clone();
  36066. this._cachedDirection = this._lightDirection.clone();
  36067. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  36068. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  36069. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  36070. }
  36071. return this._transformMatrix;
  36072. };
  36073. ShadowGenerator.prototype.recreateShadowMap = function () {
  36074. // Track render list.
  36075. var renderList = this._shadowMap.renderList;
  36076. // Clean up existing data.
  36077. this._disposeRTTandPostProcesses();
  36078. // Reinitializes.
  36079. this._initializeGenerator();
  36080. // Reaffect the filter to ensure a correct fallback if necessary.
  36081. this.filter = this.filter;
  36082. // Reaffect the filter.
  36083. this._applyFilterValues();
  36084. // Reaffect Render List.
  36085. this._shadowMap.renderList = renderList;
  36086. };
  36087. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  36088. if (this._shadowMap2) {
  36089. this._shadowMap2.dispose();
  36090. this._shadowMap2 = null;
  36091. }
  36092. if (this._downSamplePostprocess) {
  36093. this._downSamplePostprocess.dispose();
  36094. this._downSamplePostprocess = null;
  36095. }
  36096. if (this._boxBlurPostprocess) {
  36097. this._boxBlurPostprocess.dispose();
  36098. this._boxBlurPostprocess = null;
  36099. }
  36100. if (this._kernelBlurXPostprocess) {
  36101. this._kernelBlurXPostprocess.dispose();
  36102. this._kernelBlurXPostprocess = null;
  36103. }
  36104. if (this._kernelBlurYPostprocess) {
  36105. this._kernelBlurYPostprocess.dispose();
  36106. this._kernelBlurYPostprocess = null;
  36107. }
  36108. this._blurPostProcesses = null;
  36109. };
  36110. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  36111. if (this._shadowMap) {
  36112. this._shadowMap.dispose();
  36113. this._shadowMap = null;
  36114. }
  36115. this._disposeBlurPostProcesses();
  36116. };
  36117. /**
  36118. * Disposes the ShadowGenerator.
  36119. * Returns nothing.
  36120. */
  36121. ShadowGenerator.prototype.dispose = function () {
  36122. this._disposeRTTandPostProcesses();
  36123. this._light._shadowGenerator = null;
  36124. this._light._markMeshesAsLightDirty();
  36125. };
  36126. /**
  36127. * Serializes the ShadowGenerator and returns a serializationObject.
  36128. */
  36129. ShadowGenerator.prototype.serialize = function () {
  36130. var serializationObject = {};
  36131. var shadowMap = this.getShadowMap();
  36132. serializationObject.lightId = this._light.id;
  36133. serializationObject.mapSize = shadowMap.getRenderSize();
  36134. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  36135. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  36136. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  36137. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  36138. serializationObject.usePoissonSampling = this.usePoissonSampling;
  36139. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  36140. serializationObject.depthScale = this.depthScale;
  36141. serializationObject.darkness = this.getDarkness();
  36142. serializationObject.blurBoxOffset = this.blurBoxOffset;
  36143. serializationObject.blurKernel = this.blurKernel;
  36144. serializationObject.blurScale = this.blurScale;
  36145. serializationObject.useKernelBlur = this.useKernelBlur;
  36146. serializationObject.transparencyShadow = this._transparencyShadow;
  36147. serializationObject.renderList = [];
  36148. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  36149. var mesh = shadowMap.renderList[meshIndex];
  36150. serializationObject.renderList.push(mesh.id);
  36151. }
  36152. return serializationObject;
  36153. };
  36154. /**
  36155. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  36156. */
  36157. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  36158. //casting to point light, as light is missing the position attr and typescript complains.
  36159. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  36160. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  36161. var shadowMap = shadowGenerator.getShadowMap();
  36162. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  36163. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  36164. meshes.forEach(function (mesh) {
  36165. shadowMap.renderList.push(mesh);
  36166. });
  36167. }
  36168. if (parsedShadowGenerator.usePoissonSampling) {
  36169. shadowGenerator.usePoissonSampling = true;
  36170. }
  36171. else if (parsedShadowGenerator.useExponentialShadowMap) {
  36172. shadowGenerator.useExponentialShadowMap = true;
  36173. }
  36174. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  36175. shadowGenerator.useBlurExponentialShadowMap = true;
  36176. }
  36177. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  36178. shadowGenerator.useCloseExponentialShadowMap = true;
  36179. }
  36180. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  36181. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  36182. }
  36183. else if (parsedShadowGenerator.useVarianceShadowMap) {
  36184. shadowGenerator.useExponentialShadowMap = true;
  36185. }
  36186. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  36187. shadowGenerator.useBlurExponentialShadowMap = true;
  36188. }
  36189. if (parsedShadowGenerator.depthScale) {
  36190. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  36191. }
  36192. if (parsedShadowGenerator.blurScale) {
  36193. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  36194. }
  36195. if (parsedShadowGenerator.blurBoxOffset) {
  36196. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  36197. }
  36198. if (parsedShadowGenerator.useKernelBlur) {
  36199. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  36200. }
  36201. if (parsedShadowGenerator.blurKernel) {
  36202. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  36203. }
  36204. if (parsedShadowGenerator.bias !== undefined) {
  36205. shadowGenerator.bias = parsedShadowGenerator.bias;
  36206. }
  36207. if (parsedShadowGenerator.darkness) {
  36208. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  36209. }
  36210. if (parsedShadowGenerator.transparencyShadow) {
  36211. shadowGenerator.setTransparencyShadow(true);
  36212. }
  36213. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  36214. return shadowGenerator;
  36215. };
  36216. ShadowGenerator._FILTER_NONE = 0;
  36217. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  36218. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  36219. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  36220. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  36221. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  36222. return ShadowGenerator;
  36223. }());
  36224. BABYLON.ShadowGenerator = ShadowGenerator;
  36225. })(BABYLON || (BABYLON = {}));
  36226. //# sourceMappingURL=babylon.shadowGenerator.js.map
  36227. var BABYLON;
  36228. (function (BABYLON) {
  36229. var ShadowLight = (function (_super) {
  36230. __extends(ShadowLight, _super);
  36231. function ShadowLight() {
  36232. var _this = _super !== null && _super.apply(this, arguments) || this;
  36233. _this._needProjectionMatrixCompute = true;
  36234. return _this;
  36235. }
  36236. Object.defineProperty(ShadowLight.prototype, "direction", {
  36237. get: function () {
  36238. return this._direction;
  36239. },
  36240. set: function (value) {
  36241. this._direction = value;
  36242. },
  36243. enumerable: true,
  36244. configurable: true
  36245. });
  36246. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  36247. get: function () {
  36248. return this._shadowMinZ;
  36249. },
  36250. set: function (value) {
  36251. this._shadowMinZ = value;
  36252. this.forceProjectionMatrixCompute();
  36253. },
  36254. enumerable: true,
  36255. configurable: true
  36256. });
  36257. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  36258. get: function () {
  36259. return this._shadowMaxZ;
  36260. },
  36261. set: function (value) {
  36262. this._shadowMaxZ = value;
  36263. this.forceProjectionMatrixCompute();
  36264. },
  36265. enumerable: true,
  36266. configurable: true
  36267. });
  36268. /**
  36269. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  36270. */
  36271. ShadowLight.prototype.computeTransformedInformation = function () {
  36272. if (this.parent && this.parent.getWorldMatrix) {
  36273. if (!this.transformedPosition) {
  36274. this.transformedPosition = BABYLON.Vector3.Zero();
  36275. }
  36276. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  36277. // In case the direction is present.
  36278. if (this.direction) {
  36279. if (!this.transformedDirection) {
  36280. this.transformedDirection = BABYLON.Vector3.Zero();
  36281. }
  36282. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  36283. }
  36284. return true;
  36285. }
  36286. return false;
  36287. };
  36288. /**
  36289. * Return the depth scale used for the shadow map.
  36290. */
  36291. ShadowLight.prototype.getDepthScale = function () {
  36292. return 50.0;
  36293. };
  36294. /**
  36295. * Returns the light direction (Vector3) for any passed face index.
  36296. */
  36297. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  36298. return this.transformedDirection ? this.transformedDirection : this.direction;
  36299. };
  36300. /**
  36301. * Returns the DirectionalLight absolute position in the World.
  36302. */
  36303. ShadowLight.prototype.getAbsolutePosition = function () {
  36304. return this.transformedPosition ? this.transformedPosition : this.position;
  36305. };
  36306. /**
  36307. * Sets the DirectionalLight direction toward the passed target (Vector3).
  36308. * Returns the updated DirectionalLight direction (Vector3).
  36309. */
  36310. ShadowLight.prototype.setDirectionToTarget = function (target) {
  36311. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  36312. return this.direction;
  36313. };
  36314. /**
  36315. * Returns the light rotation (Vector3).
  36316. */
  36317. ShadowLight.prototype.getRotation = function () {
  36318. this.direction.normalize();
  36319. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  36320. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  36321. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  36322. };
  36323. /**
  36324. * Boolean : false by default.
  36325. */
  36326. ShadowLight.prototype.needCube = function () {
  36327. return false;
  36328. };
  36329. /**
  36330. * Specifies wether or not the projection matrix should be recomputed this frame.
  36331. */
  36332. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  36333. return this._needProjectionMatrixCompute;
  36334. };
  36335. /**
  36336. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  36337. */
  36338. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  36339. this._needProjectionMatrixCompute = true;
  36340. };
  36341. /**
  36342. * Get the world matrix of the sahdow lights.
  36343. */
  36344. ShadowLight.prototype._getWorldMatrix = function () {
  36345. if (!this._worldMatrix) {
  36346. this._worldMatrix = BABYLON.Matrix.Identity();
  36347. }
  36348. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  36349. return this._worldMatrix;
  36350. };
  36351. /**
  36352. * Gets the minZ used for shadow according to both the scene and the light.
  36353. * @param activeCamera
  36354. */
  36355. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  36356. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  36357. };
  36358. /**
  36359. * Gets the maxZ used for shadow according to both the scene and the light.
  36360. * @param activeCamera
  36361. */
  36362. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  36363. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  36364. };
  36365. /**
  36366. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  36367. * Returns the light.
  36368. */
  36369. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36370. if (this.customProjectionMatrixBuilder) {
  36371. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  36372. }
  36373. else {
  36374. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36375. }
  36376. return this;
  36377. };
  36378. __decorate([
  36379. BABYLON.serializeAsVector3()
  36380. ], ShadowLight.prototype, "position", void 0);
  36381. __decorate([
  36382. BABYLON.serializeAsVector3()
  36383. ], ShadowLight.prototype, "direction", null);
  36384. __decorate([
  36385. BABYLON.serialize()
  36386. ], ShadowLight.prototype, "shadowMinZ", null);
  36387. __decorate([
  36388. BABYLON.serialize()
  36389. ], ShadowLight.prototype, "shadowMaxZ", null);
  36390. return ShadowLight;
  36391. }(BABYLON.Light));
  36392. BABYLON.ShadowLight = ShadowLight;
  36393. })(BABYLON || (BABYLON = {}));
  36394. //# sourceMappingURL=babylon.shadowLight.js.map
  36395. var BABYLON;
  36396. (function (BABYLON) {
  36397. var PointLight = (function (_super) {
  36398. __extends(PointLight, _super);
  36399. /**
  36400. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  36401. * A PointLight emits the light in every direction.
  36402. * It can cast shadows.
  36403. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  36404. * ```javascript
  36405. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  36406. * ```
  36407. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36408. */
  36409. function PointLight(name, position, scene) {
  36410. var _this = _super.call(this, name, scene) || this;
  36411. _this._shadowAngle = Math.PI / 2;
  36412. _this.position = position;
  36413. return _this;
  36414. }
  36415. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  36416. /**
  36417. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36418. * This specifies what angle the shadow will use to be created.
  36419. *
  36420. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36421. */
  36422. get: function () {
  36423. return this._shadowAngle;
  36424. },
  36425. /**
  36426. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36427. * This specifies what angle the shadow will use to be created.
  36428. *
  36429. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36430. */
  36431. set: function (value) {
  36432. this._shadowAngle = value;
  36433. this.forceProjectionMatrixCompute();
  36434. },
  36435. enumerable: true,
  36436. configurable: true
  36437. });
  36438. Object.defineProperty(PointLight.prototype, "direction", {
  36439. get: function () {
  36440. return this._direction;
  36441. },
  36442. /**
  36443. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36444. */
  36445. set: function (value) {
  36446. var previousNeedCube = this.needCube();
  36447. this._direction = value;
  36448. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  36449. this._shadowGenerator.recreateShadowMap();
  36450. }
  36451. },
  36452. enumerable: true,
  36453. configurable: true
  36454. });
  36455. /**
  36456. * Returns the string "PointLight"
  36457. */
  36458. PointLight.prototype.getClassName = function () {
  36459. return "PointLight";
  36460. };
  36461. /**
  36462. * Returns the integer 0.
  36463. */
  36464. PointLight.prototype.getTypeID = function () {
  36465. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  36466. };
  36467. /**
  36468. * Specifies wether or not the shadowmap should be a cube texture.
  36469. */
  36470. PointLight.prototype.needCube = function () {
  36471. return !this.direction;
  36472. };
  36473. /**
  36474. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  36475. */
  36476. PointLight.prototype.getShadowDirection = function (faceIndex) {
  36477. if (this.direction) {
  36478. return _super.prototype.getShadowDirection.call(this, faceIndex);
  36479. }
  36480. else {
  36481. switch (faceIndex) {
  36482. case 0:
  36483. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  36484. case 1:
  36485. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  36486. case 2:
  36487. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  36488. case 3:
  36489. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  36490. case 4:
  36491. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  36492. case 5:
  36493. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  36494. }
  36495. }
  36496. return BABYLON.Vector3.Zero();
  36497. };
  36498. /**
  36499. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  36500. * - fov = PI / 2
  36501. * - aspect ratio : 1.0
  36502. * - z-near and far equal to the active camera minZ and maxZ.
  36503. * Returns the PointLight.
  36504. */
  36505. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36506. var activeCamera = this.getScene().activeCamera;
  36507. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36508. };
  36509. PointLight.prototype._buildUniformLayout = function () {
  36510. this._uniformBuffer.addUniform("vLightData", 4);
  36511. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36512. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36513. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36514. this._uniformBuffer.addUniform("depthValues", 2);
  36515. this._uniformBuffer.create();
  36516. };
  36517. /**
  36518. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  36519. * Returns the PointLight.
  36520. */
  36521. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  36522. if (this.computeTransformedInformation()) {
  36523. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  36524. return this;
  36525. }
  36526. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  36527. return this;
  36528. };
  36529. __decorate([
  36530. BABYLON.serialize()
  36531. ], PointLight.prototype, "shadowAngle", null);
  36532. return PointLight;
  36533. }(BABYLON.ShadowLight));
  36534. BABYLON.PointLight = PointLight;
  36535. })(BABYLON || (BABYLON = {}));
  36536. //# sourceMappingURL=babylon.pointLight.js.map
  36537. /// <reference path="babylon.light.ts" />
  36538. var BABYLON;
  36539. (function (BABYLON) {
  36540. var DirectionalLight = (function (_super) {
  36541. __extends(DirectionalLight, _super);
  36542. /**
  36543. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36544. * The directional light is emitted from everywhere in the given direction.
  36545. * It can cast shawdows.
  36546. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36547. */
  36548. function DirectionalLight(name, direction, scene) {
  36549. var _this = _super.call(this, name, scene) || this;
  36550. _this._shadowFrustumSize = 0;
  36551. _this._shadowOrthoScale = 0.5;
  36552. _this.autoUpdateExtends = true;
  36553. // Cache
  36554. _this._orthoLeft = Number.MAX_VALUE;
  36555. _this._orthoRight = Number.MIN_VALUE;
  36556. _this._orthoTop = Number.MIN_VALUE;
  36557. _this._orthoBottom = Number.MAX_VALUE;
  36558. _this.position = direction.scale(-1.0);
  36559. _this.direction = direction;
  36560. return _this;
  36561. }
  36562. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36563. /**
  36564. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36565. */
  36566. get: function () {
  36567. return this._shadowFrustumSize;
  36568. },
  36569. /**
  36570. * Specifies a fix frustum size for the shadow generation.
  36571. */
  36572. set: function (value) {
  36573. this._shadowFrustumSize = value;
  36574. this.forceProjectionMatrixCompute();
  36575. },
  36576. enumerable: true,
  36577. configurable: true
  36578. });
  36579. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36580. get: function () {
  36581. return this._shadowOrthoScale;
  36582. },
  36583. set: function (value) {
  36584. this._shadowOrthoScale = value;
  36585. this.forceProjectionMatrixCompute();
  36586. },
  36587. enumerable: true,
  36588. configurable: true
  36589. });
  36590. /**
  36591. * Returns the string "DirectionalLight".
  36592. */
  36593. DirectionalLight.prototype.getClassName = function () {
  36594. return "DirectionalLight";
  36595. };
  36596. /**
  36597. * Returns the integer 1.
  36598. */
  36599. DirectionalLight.prototype.getTypeID = function () {
  36600. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36601. };
  36602. /**
  36603. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36604. * Returns the DirectionalLight Shadow projection matrix.
  36605. */
  36606. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36607. if (this.shadowFrustumSize > 0) {
  36608. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36609. }
  36610. else {
  36611. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36612. }
  36613. };
  36614. /**
  36615. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36616. * Returns the DirectionalLight Shadow projection matrix.
  36617. */
  36618. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36619. var activeCamera = this.getScene().activeCamera;
  36620. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36621. };
  36622. /**
  36623. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36624. * Returns the DirectionalLight Shadow projection matrix.
  36625. */
  36626. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36627. var activeCamera = this.getScene().activeCamera;
  36628. // Check extends
  36629. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36630. var tempVector3 = BABYLON.Vector3.Zero();
  36631. this._orthoLeft = Number.MAX_VALUE;
  36632. this._orthoRight = Number.MIN_VALUE;
  36633. this._orthoTop = Number.MIN_VALUE;
  36634. this._orthoBottom = Number.MAX_VALUE;
  36635. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36636. var mesh = renderList[meshIndex];
  36637. if (!mesh) {
  36638. continue;
  36639. }
  36640. var boundingInfo = mesh.getBoundingInfo();
  36641. if (!boundingInfo) {
  36642. continue;
  36643. }
  36644. var boundingBox = boundingInfo.boundingBox;
  36645. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36646. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36647. if (tempVector3.x < this._orthoLeft)
  36648. this._orthoLeft = tempVector3.x;
  36649. if (tempVector3.y < this._orthoBottom)
  36650. this._orthoBottom = tempVector3.y;
  36651. if (tempVector3.x > this._orthoRight)
  36652. this._orthoRight = tempVector3.x;
  36653. if (tempVector3.y > this._orthoTop)
  36654. this._orthoTop = tempVector3.y;
  36655. }
  36656. }
  36657. }
  36658. var xOffset = this._orthoRight - this._orthoLeft;
  36659. var yOffset = this._orthoTop - this._orthoBottom;
  36660. 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);
  36661. };
  36662. DirectionalLight.prototype._buildUniformLayout = function () {
  36663. this._uniformBuffer.addUniform("vLightData", 4);
  36664. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36665. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36666. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36667. this._uniformBuffer.addUniform("depthValues", 2);
  36668. this._uniformBuffer.create();
  36669. };
  36670. /**
  36671. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  36672. * Returns the DirectionalLight.
  36673. */
  36674. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  36675. if (this.computeTransformedInformation()) {
  36676. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  36677. return this;
  36678. }
  36679. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  36680. return this;
  36681. };
  36682. /**
  36683. * Gets the minZ used for shadow according to both the scene and the light.
  36684. *
  36685. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36686. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36687. * @param activeCamera
  36688. */
  36689. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  36690. return 1;
  36691. };
  36692. /**
  36693. * Gets the maxZ used for shadow according to both the scene and the light.
  36694. *
  36695. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36696. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36697. * @param activeCamera
  36698. */
  36699. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  36700. return 1;
  36701. };
  36702. __decorate([
  36703. BABYLON.serialize()
  36704. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  36705. __decorate([
  36706. BABYLON.serialize()
  36707. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  36708. __decorate([
  36709. BABYLON.serialize()
  36710. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  36711. return DirectionalLight;
  36712. }(BABYLON.ShadowLight));
  36713. BABYLON.DirectionalLight = DirectionalLight;
  36714. })(BABYLON || (BABYLON = {}));
  36715. //# sourceMappingURL=babylon.directionalLight.js.map
  36716. var BABYLON;
  36717. (function (BABYLON) {
  36718. var SpotLight = (function (_super) {
  36719. __extends(SpotLight, _super);
  36720. /**
  36721. * Creates a SpotLight object in the scene with the passed parameters :
  36722. * - `position` (Vector3) is the initial SpotLight position,
  36723. * - `direction` (Vector3) is the initial SpotLight direction,
  36724. * - `angle` (float, in radians) is the spot light cone angle,
  36725. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  36726. * A spot light is a simply light oriented cone.
  36727. * It can cast shadows.
  36728. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36729. */
  36730. function SpotLight(name, position, direction, angle, exponent, scene) {
  36731. var _this = _super.call(this, name, scene) || this;
  36732. _this.position = position;
  36733. _this.direction = direction;
  36734. _this.angle = angle;
  36735. _this.exponent = exponent;
  36736. return _this;
  36737. }
  36738. Object.defineProperty(SpotLight.prototype, "angle", {
  36739. get: function () {
  36740. return this._angle;
  36741. },
  36742. set: function (value) {
  36743. this._angle = value;
  36744. this.forceProjectionMatrixCompute();
  36745. },
  36746. enumerable: true,
  36747. configurable: true
  36748. });
  36749. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  36750. get: function () {
  36751. return this._shadowAngleScale;
  36752. },
  36753. /**
  36754. * Allows scaling the angle of the light for shadow generation only.
  36755. */
  36756. set: function (value) {
  36757. this._shadowAngleScale = value;
  36758. this.forceProjectionMatrixCompute();
  36759. },
  36760. enumerable: true,
  36761. configurable: true
  36762. });
  36763. /**
  36764. * Returns the string "SpotLight".
  36765. */
  36766. SpotLight.prototype.getClassName = function () {
  36767. return "SpotLight";
  36768. };
  36769. /**
  36770. * Returns the integer 2.
  36771. */
  36772. SpotLight.prototype.getTypeID = function () {
  36773. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  36774. };
  36775. /**
  36776. * 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.
  36777. * Returns the SpotLight.
  36778. */
  36779. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36780. var activeCamera = this.getScene().activeCamera;
  36781. this._shadowAngleScale = this._shadowAngleScale || 1;
  36782. var angle = this._shadowAngleScale * this._angle;
  36783. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36784. };
  36785. SpotLight.prototype._buildUniformLayout = function () {
  36786. this._uniformBuffer.addUniform("vLightData", 4);
  36787. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36788. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36789. this._uniformBuffer.addUniform("vLightDirection", 3);
  36790. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36791. this._uniformBuffer.addUniform("depthValues", 2);
  36792. this._uniformBuffer.create();
  36793. };
  36794. /**
  36795. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  36796. * Return the SpotLight.
  36797. */
  36798. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  36799. var normalizeDirection;
  36800. if (this.computeTransformedInformation()) {
  36801. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  36802. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  36803. }
  36804. else {
  36805. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  36806. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36807. }
  36808. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  36809. return this;
  36810. };
  36811. __decorate([
  36812. BABYLON.serialize()
  36813. ], SpotLight.prototype, "angle", null);
  36814. __decorate([
  36815. BABYLON.serialize()
  36816. /**
  36817. * Allows scaling the angle of the light for shadow generation only.
  36818. */
  36819. ], SpotLight.prototype, "shadowAngleScale", null);
  36820. __decorate([
  36821. BABYLON.serialize()
  36822. ], SpotLight.prototype, "exponent", void 0);
  36823. return SpotLight;
  36824. }(BABYLON.ShadowLight));
  36825. BABYLON.SpotLight = SpotLight;
  36826. })(BABYLON || (BABYLON = {}));
  36827. //# sourceMappingURL=babylon.spotLight.js.map
  36828. var BABYLON;
  36829. (function (BABYLON) {
  36830. var MultiMaterial = (function (_super) {
  36831. __extends(MultiMaterial, _super);
  36832. function MultiMaterial(name, scene) {
  36833. var _this = _super.call(this, name, scene, true) || this;
  36834. scene.multiMaterials.push(_this);
  36835. _this.subMaterials = new Array();
  36836. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  36837. return _this;
  36838. }
  36839. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  36840. get: function () {
  36841. return this._subMaterials;
  36842. },
  36843. set: function (value) {
  36844. this._subMaterials = value;
  36845. this._hookArray(value);
  36846. },
  36847. enumerable: true,
  36848. configurable: true
  36849. });
  36850. MultiMaterial.prototype._hookArray = function (array) {
  36851. var _this = this;
  36852. var oldPush = array.push;
  36853. array.push = function () {
  36854. var items = [];
  36855. for (var _i = 0; _i < arguments.length; _i++) {
  36856. items[_i] = arguments[_i];
  36857. }
  36858. var result = oldPush.apply(array, items);
  36859. _this._markAllSubMeshesAsTexturesDirty();
  36860. return result;
  36861. };
  36862. var oldSplice = array.splice;
  36863. array.splice = function (index, deleteCount) {
  36864. var deleted = oldSplice.apply(array, [index, deleteCount]);
  36865. _this._markAllSubMeshesAsTexturesDirty();
  36866. return deleted;
  36867. };
  36868. };
  36869. // Properties
  36870. MultiMaterial.prototype.getSubMaterial = function (index) {
  36871. if (index < 0 || index >= this.subMaterials.length) {
  36872. return this.getScene().defaultMaterial;
  36873. }
  36874. return this.subMaterials[index];
  36875. };
  36876. MultiMaterial.prototype.getActiveTextures = function () {
  36877. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  36878. var _a;
  36879. };
  36880. // Methods
  36881. MultiMaterial.prototype.getClassName = function () {
  36882. return "MultiMaterial";
  36883. };
  36884. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36885. for (var index = 0; index < this.subMaterials.length; index++) {
  36886. var subMaterial = this.subMaterials[index];
  36887. if (subMaterial) {
  36888. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  36889. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  36890. return false;
  36891. }
  36892. continue;
  36893. }
  36894. if (!this.subMaterials[index].isReady(mesh)) {
  36895. return false;
  36896. }
  36897. }
  36898. }
  36899. return true;
  36900. };
  36901. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  36902. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  36903. for (var index = 0; index < this.subMaterials.length; index++) {
  36904. var subMaterial = null;
  36905. if (cloneChildren) {
  36906. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  36907. }
  36908. else {
  36909. subMaterial = this.subMaterials[index];
  36910. }
  36911. newMultiMaterial.subMaterials.push(subMaterial);
  36912. }
  36913. return newMultiMaterial;
  36914. };
  36915. MultiMaterial.prototype.serialize = function () {
  36916. var serializationObject = {};
  36917. serializationObject.name = this.name;
  36918. serializationObject.id = this.id;
  36919. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36920. serializationObject.materials = [];
  36921. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  36922. var subMat = this.subMaterials[matIndex];
  36923. if (subMat) {
  36924. serializationObject.materials.push(subMat.id);
  36925. }
  36926. else {
  36927. serializationObject.materials.push(null);
  36928. }
  36929. }
  36930. return serializationObject;
  36931. };
  36932. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36933. var scene = this.getScene();
  36934. if (!scene) {
  36935. return;
  36936. }
  36937. var index = scene.multiMaterials.indexOf(this);
  36938. if (index >= 0) {
  36939. scene.multiMaterials.splice(index, 1);
  36940. }
  36941. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36942. };
  36943. return MultiMaterial;
  36944. }(BABYLON.Material));
  36945. BABYLON.MultiMaterial = MultiMaterial;
  36946. })(BABYLON || (BABYLON = {}));
  36947. //# sourceMappingURL=babylon.multiMaterial.js.map
  36948. var BABYLON;
  36949. (function (BABYLON) {
  36950. var PBRMaterialDefines = (function (_super) {
  36951. __extends(PBRMaterialDefines, _super);
  36952. function PBRMaterialDefines() {
  36953. var _this = _super.call(this) || this;
  36954. _this.PBR = true;
  36955. _this.MAINUV1 = false;
  36956. _this.MAINUV2 = false;
  36957. _this.UV1 = false;
  36958. _this.UV2 = false;
  36959. _this.ALBEDO = false;
  36960. _this.ALBEDODIRECTUV = 0;
  36961. _this.VERTEXCOLOR = false;
  36962. _this.AMBIENT = false;
  36963. _this.AMBIENTDIRECTUV = 0;
  36964. _this.AMBIENTINGRAYSCALE = false;
  36965. _this.OPACITY = false;
  36966. _this.VERTEXALPHA = false;
  36967. _this.OPACITYDIRECTUV = 0;
  36968. _this.OPACITYRGB = false;
  36969. _this.ALPHATEST = false;
  36970. _this.ALPHABLEND = false;
  36971. _this.ALPHAFROMALBEDO = false;
  36972. _this.ALPHATESTVALUE = 0.5;
  36973. _this.SPECULAROVERALPHA = false;
  36974. _this.RADIANCEOVERALPHA = false;
  36975. _this.ALPHAFRESNEL = false;
  36976. _this.PREMULTIPLYALPHA = false;
  36977. _this.EMISSIVE = false;
  36978. _this.EMISSIVEDIRECTUV = 0;
  36979. _this.REFLECTIVITY = false;
  36980. _this.REFLECTIVITYDIRECTUV = 0;
  36981. _this.SPECULARTERM = false;
  36982. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36983. _this.MICROSURFACEAUTOMATIC = false;
  36984. _this.LODBASEDMICROSFURACE = false;
  36985. _this.MICROSURFACEMAP = false;
  36986. _this.MICROSURFACEMAPDIRECTUV = 0;
  36987. _this.METALLICWORKFLOW = false;
  36988. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36989. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36990. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36991. _this.AOSTOREINMETALMAPRED = false;
  36992. _this.ENVIRONMENTBRDF = false;
  36993. _this.NORMAL = false;
  36994. _this.TANGENT = false;
  36995. _this.BUMP = false;
  36996. _this.BUMPDIRECTUV = 0;
  36997. _this.PARALLAX = false;
  36998. _this.PARALLAXOCCLUSION = false;
  36999. _this.NORMALXYSCALE = true;
  37000. _this.LIGHTMAP = false;
  37001. _this.LIGHTMAPDIRECTUV = 0;
  37002. _this.USELIGHTMAPASSHADOWMAP = false;
  37003. _this.REFLECTION = false;
  37004. _this.REFLECTIONMAP_3D = false;
  37005. _this.REFLECTIONMAP_SPHERICAL = false;
  37006. _this.REFLECTIONMAP_PLANAR = false;
  37007. _this.REFLECTIONMAP_CUBIC = false;
  37008. _this.REFLECTIONMAP_PROJECTION = false;
  37009. _this.REFLECTIONMAP_SKYBOX = false;
  37010. _this.REFLECTIONMAP_EXPLICIT = false;
  37011. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37012. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37013. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37014. _this.INVERTCUBICMAP = false;
  37015. _this.USESPHERICALFROMREFLECTIONMAP = false;
  37016. _this.USESPHERICALINFRAGMENT = false;
  37017. _this.REFLECTIONMAP_OPPOSITEZ = false;
  37018. _this.LODINREFLECTIONALPHA = false;
  37019. _this.GAMMAREFLECTION = false;
  37020. _this.REFRACTION = false;
  37021. _this.REFRACTIONMAP_3D = false;
  37022. _this.REFRACTIONMAP_OPPOSITEZ = false;
  37023. _this.LODINREFRACTIONALPHA = false;
  37024. _this.GAMMAREFRACTION = false;
  37025. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  37026. _this.INSTANCES = false;
  37027. _this.NUM_BONE_INFLUENCERS = 0;
  37028. _this.BonesPerMesh = 0;
  37029. _this.MORPHTARGETS = false;
  37030. _this.MORPHTARGETS_NORMAL = false;
  37031. _this.MORPHTARGETS_TANGENT = false;
  37032. _this.NUM_MORPH_INFLUENCERS = 0;
  37033. _this.IMAGEPROCESSING = false;
  37034. _this.VIGNETTE = false;
  37035. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  37036. _this.VIGNETTEBLENDMODEOPAQUE = false;
  37037. _this.TONEMAPPING = false;
  37038. _this.CONTRAST = false;
  37039. _this.COLORCURVES = false;
  37040. _this.COLORGRADING = false;
  37041. _this.SAMPLER3DGREENDEPTH = false;
  37042. _this.SAMPLER3DBGRMAP = false;
  37043. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  37044. _this.EXPOSURE = false;
  37045. _this.USEPHYSICALLIGHTFALLOFF = false;
  37046. _this.TWOSIDEDLIGHTING = false;
  37047. _this.SHADOWFLOAT = false;
  37048. _this.USERIGHTHANDEDSYSTEM = false;
  37049. _this.CLIPPLANE = false;
  37050. _this.POINTSIZE = false;
  37051. _this.FOG = false;
  37052. _this.LOGARITHMICDEPTH = false;
  37053. _this.FORCENORMALFORWARD = false;
  37054. _this.rebuild();
  37055. return _this;
  37056. }
  37057. PBRMaterialDefines.prototype.reset = function () {
  37058. _super.prototype.reset.call(this);
  37059. this.ALPHATESTVALUE = 0.5;
  37060. this.PBR = true;
  37061. };
  37062. return PBRMaterialDefines;
  37063. }(BABYLON.MaterialDefines));
  37064. /**
  37065. * The Physically based material base class of BJS.
  37066. *
  37067. * This offers the main features of a standard PBR material.
  37068. * For more information, please refer to the documentation :
  37069. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37070. */
  37071. var PBRBaseMaterial = (function (_super) {
  37072. __extends(PBRBaseMaterial, _super);
  37073. /**
  37074. * Instantiates a new PBRMaterial instance.
  37075. *
  37076. * @param name The material name
  37077. * @param scene The scene the material will be use in.
  37078. */
  37079. function PBRBaseMaterial(name, scene) {
  37080. var _this = _super.call(this, name, scene) || this;
  37081. /**
  37082. * Intensity of the direct lights e.g. the four lights available in your scene.
  37083. * This impacts both the direct diffuse and specular highlights.
  37084. */
  37085. _this._directIntensity = 1.0;
  37086. /**
  37087. * Intensity of the emissive part of the material.
  37088. * This helps controlling the emissive effect without modifying the emissive color.
  37089. */
  37090. _this._emissiveIntensity = 1.0;
  37091. /**
  37092. * Intensity of the environment e.g. how much the environment will light the object
  37093. * either through harmonics for rough material or through the refelction for shiny ones.
  37094. */
  37095. _this._environmentIntensity = 1.0;
  37096. /**
  37097. * This is a special control allowing the reduction of the specular highlights coming from the
  37098. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37099. */
  37100. _this._specularIntensity = 1.0;
  37101. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  37102. /**
  37103. * Debug Control allowing disabling the bump map on this material.
  37104. */
  37105. _this._disableBumpMap = false;
  37106. /**
  37107. * AKA Occlusion Texture Intensity in other nomenclature.
  37108. */
  37109. _this._ambientTextureStrength = 1.0;
  37110. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  37111. /**
  37112. * AKA Diffuse Color in other nomenclature.
  37113. */
  37114. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  37115. /**
  37116. * AKA Specular Color in other nomenclature.
  37117. */
  37118. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37119. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  37120. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  37121. /**
  37122. * AKA Glossiness in other nomenclature.
  37123. */
  37124. _this._microSurface = 0.9;
  37125. /**
  37126. * source material index of refraction (IOR)' / 'destination material IOR.
  37127. */
  37128. _this._indexOfRefraction = 0.66;
  37129. /**
  37130. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37131. */
  37132. _this._invertRefractionY = false;
  37133. /**
  37134. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37135. * Materials half opaque for instance using refraction could benefit from this control.
  37136. */
  37137. _this._linkRefractionWithTransparency = false;
  37138. _this._useLightmapAsShadowmap = false;
  37139. /**
  37140. * Specifies that the alpha is coming form the albedo channel alpha channel.
  37141. */
  37142. _this._useAlphaFromAlbedoTexture = false;
  37143. /**
  37144. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37145. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37146. */
  37147. _this._useSpecularOverAlpha = true;
  37148. /**
  37149. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37150. */
  37151. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  37152. /**
  37153. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37154. */
  37155. _this._useRoughnessFromMetallicTextureAlpha = true;
  37156. /**
  37157. * Specifies if the metallic texture contains the roughness information in its green channel.
  37158. */
  37159. _this._useRoughnessFromMetallicTextureGreen = false;
  37160. /**
  37161. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37162. */
  37163. _this._useMetallnessFromMetallicTextureBlue = false;
  37164. /**
  37165. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37166. */
  37167. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  37168. /**
  37169. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37170. */
  37171. _this._useAmbientInGrayScale = false;
  37172. /**
  37173. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37174. * The material will try to infer what glossiness each pixel should be.
  37175. */
  37176. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  37177. /**
  37178. * BJS is using an harcoded light falloff based on a manually sets up range.
  37179. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37180. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37181. */
  37182. _this._usePhysicalLightFalloff = true;
  37183. /**
  37184. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37185. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37186. */
  37187. _this._useRadianceOverAlpha = true;
  37188. /**
  37189. * Allows using the bump map in parallax mode.
  37190. */
  37191. _this._useParallax = false;
  37192. /**
  37193. * Allows using the bump map in parallax occlusion mode.
  37194. */
  37195. _this._useParallaxOcclusion = false;
  37196. /**
  37197. * Controls the scale bias of the parallax mode.
  37198. */
  37199. _this._parallaxScaleBias = 0.05;
  37200. /**
  37201. * If sets to true, disables all the lights affecting the material.
  37202. */
  37203. _this._disableLighting = false;
  37204. /**
  37205. * Number of Simultaneous lights allowed on the material.
  37206. */
  37207. _this._maxSimultaneousLights = 4;
  37208. /**
  37209. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  37210. */
  37211. _this._invertNormalMapX = false;
  37212. /**
  37213. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  37214. */
  37215. _this._invertNormalMapY = false;
  37216. /**
  37217. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37218. */
  37219. _this._twoSidedLighting = false;
  37220. /**
  37221. * Defines the alpha limits in alpha test mode.
  37222. */
  37223. _this._alphaCutOff = 0.4;
  37224. /**
  37225. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37226. */
  37227. _this._forceAlphaTest = false;
  37228. /**
  37229. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  37230. * in your scene composition.
  37231. */
  37232. _this._preMultiplyAlpha = false;
  37233. /**
  37234. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37235. * And/Or occlude the blended part.
  37236. */
  37237. _this._useAlphaFresnel = false;
  37238. /**
  37239. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  37240. * from cos thetav and roughness:
  37241. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  37242. */
  37243. _this._environmentBRDFTexture = null;
  37244. /**
  37245. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37246. */
  37247. _this._forceIrradianceInFragment = false;
  37248. /**
  37249. * Force normal to face away from face.
  37250. * (Temporary internal fix to remove before 3.1)
  37251. */
  37252. _this._forceNormalForward = false;
  37253. _this._renderTargets = new BABYLON.SmartArray(16);
  37254. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  37255. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  37256. _this._tempColor = new BABYLON.Color3();
  37257. // Setup the default processing configuration to the scene.
  37258. _this._attachImageProcessingConfiguration(null);
  37259. _this.getRenderTargetTextures = function () {
  37260. _this._renderTargets.reset();
  37261. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  37262. _this._renderTargets.push(_this._reflectionTexture);
  37263. }
  37264. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  37265. _this._renderTargets.push(_this._refractionTexture);
  37266. }
  37267. return _this._renderTargets;
  37268. };
  37269. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37270. return _this;
  37271. }
  37272. /**
  37273. * Attaches a new image processing configuration to the PBR Material.
  37274. * @param configuration
  37275. */
  37276. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  37277. var _this = this;
  37278. if (configuration === this._imageProcessingConfiguration) {
  37279. return;
  37280. }
  37281. // Detaches observer.
  37282. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37283. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37284. }
  37285. // Pick the scene configuration if needed.
  37286. if (!configuration) {
  37287. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  37288. }
  37289. else {
  37290. this._imageProcessingConfiguration = configuration;
  37291. }
  37292. // Attaches observer.
  37293. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  37294. _this._markAllSubMeshesAsImageProcessingDirty();
  37295. });
  37296. };
  37297. PBRBaseMaterial.prototype.getClassName = function () {
  37298. return "PBRBaseMaterial";
  37299. };
  37300. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  37301. get: function () {
  37302. return this._useLogarithmicDepth;
  37303. },
  37304. set: function (value) {
  37305. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37306. },
  37307. enumerable: true,
  37308. configurable: true
  37309. });
  37310. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  37311. if (this._linkRefractionWithTransparency) {
  37312. return false;
  37313. }
  37314. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  37315. };
  37316. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  37317. if (this._forceAlphaTest) {
  37318. return true;
  37319. }
  37320. if (this._linkRefractionWithTransparency) {
  37321. return false;
  37322. }
  37323. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  37324. };
  37325. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  37326. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  37327. };
  37328. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  37329. return this._albedoTexture;
  37330. };
  37331. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37332. if (this.isFrozen) {
  37333. if (this._wasPreviouslyReady) {
  37334. return true;
  37335. }
  37336. }
  37337. if (!subMesh._materialDefines) {
  37338. subMesh._materialDefines = new PBRMaterialDefines();
  37339. }
  37340. var scene = this.getScene();
  37341. var defines = subMesh._materialDefines;
  37342. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37343. if (defines._renderId === scene.getRenderId()) {
  37344. return true;
  37345. }
  37346. }
  37347. var engine = scene.getEngine();
  37348. // Lights
  37349. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37350. defines._needNormals = true;
  37351. // Textures
  37352. if (defines._areTexturesDirty) {
  37353. defines._needUVs = false;
  37354. if (scene.texturesEnabled) {
  37355. if (scene.getEngine().getCaps().textureLOD) {
  37356. defines.LODBASEDMICROSFURACE = true;
  37357. }
  37358. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37359. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  37360. return false;
  37361. }
  37362. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  37363. }
  37364. else {
  37365. defines.ALBEDO = false;
  37366. }
  37367. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37368. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37369. return false;
  37370. }
  37371. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37372. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  37373. }
  37374. else {
  37375. defines.AMBIENT = false;
  37376. }
  37377. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37378. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37379. return false;
  37380. }
  37381. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37382. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37383. }
  37384. else {
  37385. defines.OPACITY = false;
  37386. }
  37387. var reflectionTexture = this._getReflectionTexture();
  37388. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37389. if (!reflectionTexture.isReadyOrNotBlocking()) {
  37390. return false;
  37391. }
  37392. defines.REFLECTION = true;
  37393. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  37394. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  37395. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37396. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  37397. defines.INVERTCUBICMAP = true;
  37398. }
  37399. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  37400. switch (reflectionTexture.coordinatesMode) {
  37401. case BABYLON.Texture.CUBIC_MODE:
  37402. case BABYLON.Texture.INVCUBIC_MODE:
  37403. defines.REFLECTIONMAP_CUBIC = true;
  37404. break;
  37405. case BABYLON.Texture.EXPLICIT_MODE:
  37406. defines.REFLECTIONMAP_EXPLICIT = true;
  37407. break;
  37408. case BABYLON.Texture.PLANAR_MODE:
  37409. defines.REFLECTIONMAP_PLANAR = true;
  37410. break;
  37411. case BABYLON.Texture.PROJECTION_MODE:
  37412. defines.REFLECTIONMAP_PROJECTION = true;
  37413. break;
  37414. case BABYLON.Texture.SKYBOX_MODE:
  37415. defines.REFLECTIONMAP_SKYBOX = true;
  37416. break;
  37417. case BABYLON.Texture.SPHERICAL_MODE:
  37418. defines.REFLECTIONMAP_SPHERICAL = true;
  37419. break;
  37420. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37421. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  37422. break;
  37423. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37424. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  37425. break;
  37426. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37427. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  37428. break;
  37429. }
  37430. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  37431. if (reflectionTexture.sphericalPolynomial) {
  37432. defines.USESPHERICALFROMREFLECTIONMAP = true;
  37433. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  37434. defines.USESPHERICALINFRAGMENT = true;
  37435. }
  37436. }
  37437. }
  37438. }
  37439. else {
  37440. defines.REFLECTION = false;
  37441. defines.REFLECTIONMAP_3D = false;
  37442. defines.REFLECTIONMAP_SPHERICAL = false;
  37443. defines.REFLECTIONMAP_PLANAR = false;
  37444. defines.REFLECTIONMAP_CUBIC = false;
  37445. defines.REFLECTIONMAP_PROJECTION = false;
  37446. defines.REFLECTIONMAP_SKYBOX = false;
  37447. defines.REFLECTIONMAP_EXPLICIT = false;
  37448. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37449. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37450. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37451. defines.INVERTCUBICMAP = false;
  37452. defines.USESPHERICALFROMREFLECTIONMAP = false;
  37453. defines.USESPHERICALINFRAGMENT = false;
  37454. defines.REFLECTIONMAP_OPPOSITEZ = false;
  37455. defines.LODINREFLECTIONALPHA = false;
  37456. defines.GAMMAREFLECTION = false;
  37457. }
  37458. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37459. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37460. return false;
  37461. }
  37462. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37463. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37464. }
  37465. else {
  37466. defines.LIGHTMAP = false;
  37467. }
  37468. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37469. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37470. return false;
  37471. }
  37472. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37473. }
  37474. else {
  37475. defines.EMISSIVE = false;
  37476. }
  37477. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37478. if (this._metallicTexture) {
  37479. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  37480. return false;
  37481. }
  37482. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  37483. defines.METALLICWORKFLOW = true;
  37484. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  37485. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  37486. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  37487. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  37488. }
  37489. else if (this._reflectivityTexture) {
  37490. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  37491. return false;
  37492. }
  37493. defines.METALLICWORKFLOW = false;
  37494. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  37495. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  37496. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  37497. }
  37498. else {
  37499. defines.METALLICWORKFLOW = false;
  37500. defines.REFLECTIVITY = false;
  37501. }
  37502. if (this._microSurfaceTexture) {
  37503. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  37504. return false;
  37505. }
  37506. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  37507. }
  37508. else {
  37509. defines.MICROSURFACEMAP = false;
  37510. }
  37511. }
  37512. else {
  37513. defines.REFLECTIVITY = false;
  37514. defines.MICROSURFACEMAP = false;
  37515. }
  37516. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37517. // Bump texure can not be none blocking.
  37518. if (!this._bumpTexture.isReady()) {
  37519. return false;
  37520. }
  37521. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37522. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37523. defines.PARALLAX = true;
  37524. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  37525. }
  37526. else {
  37527. defines.PARALLAX = false;
  37528. }
  37529. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  37530. }
  37531. else {
  37532. defines.BUMP = false;
  37533. }
  37534. var refractionTexture = this._getRefractionTexture();
  37535. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37536. if (!refractionTexture.isReadyOrNotBlocking()) {
  37537. return false;
  37538. }
  37539. defines.REFRACTION = true;
  37540. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  37541. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  37542. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  37543. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37544. if (this._linkRefractionWithTransparency) {
  37545. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  37546. }
  37547. }
  37548. else {
  37549. defines.REFRACTION = false;
  37550. }
  37551. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37552. // This is blocking.
  37553. if (!this._environmentBRDFTexture.isReady()) {
  37554. return false;
  37555. }
  37556. defines.ENVIRONMENTBRDF = true;
  37557. }
  37558. if (this._shouldUseAlphaFromAlbedoTexture()) {
  37559. defines.ALPHAFROMALBEDO = true;
  37560. }
  37561. }
  37562. if (this._useSpecularOverAlpha) {
  37563. defines.SPECULAROVERALPHA = true;
  37564. }
  37565. if (this._usePhysicalLightFalloff) {
  37566. defines.USEPHYSICALLIGHTFALLOFF = true;
  37567. }
  37568. if (this._useRadianceOverAlpha) {
  37569. defines.RADIANCEOVERALPHA = true;
  37570. }
  37571. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  37572. defines.METALLICWORKFLOW = true;
  37573. }
  37574. if (!this.backFaceCulling && this._twoSidedLighting) {
  37575. defines.TWOSIDEDLIGHTING = true;
  37576. }
  37577. defines.ALPHATESTVALUE = this._alphaCutOff;
  37578. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  37579. defines.ALPHABLEND = this.needAlphaBlending();
  37580. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  37581. }
  37582. if (defines._areImageProcessingDirty) {
  37583. if (!this._imageProcessingConfiguration.isReady()) {
  37584. return false;
  37585. }
  37586. this._imageProcessingConfiguration.prepareDefines(defines);
  37587. }
  37588. defines.FORCENORMALFORWARD = this._forceNormalForward;
  37589. // Misc.
  37590. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  37591. // Values that need to be evaluated on every frame
  37592. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  37593. // Attribs
  37594. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  37595. if (mesh) {
  37596. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37597. mesh.createNormals(true);
  37598. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  37599. }
  37600. }
  37601. }
  37602. // Get correct effect
  37603. if (defines.isDirty) {
  37604. defines.markAsProcessed();
  37605. scene.resetCachedMaterial();
  37606. // Fallbacks
  37607. var fallbacks = new BABYLON.EffectFallbacks();
  37608. if (defines.ENVIRONMENTBRDF) {
  37609. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  37610. }
  37611. if (defines.REFLECTION) {
  37612. fallbacks.addFallback(0, "REFLECTION");
  37613. }
  37614. if (defines.REFRACTION) {
  37615. fallbacks.addFallback(0, "REFRACTION");
  37616. }
  37617. if (defines.REFLECTIVITY) {
  37618. fallbacks.addFallback(0, "REFLECTIVITY");
  37619. }
  37620. if (defines.BUMP) {
  37621. fallbacks.addFallback(0, "BUMP");
  37622. }
  37623. if (defines.PARALLAX) {
  37624. fallbacks.addFallback(1, "PARALLAX");
  37625. }
  37626. if (defines.PARALLAXOCCLUSION) {
  37627. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  37628. }
  37629. if (defines.SPECULAROVERALPHA) {
  37630. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  37631. }
  37632. if (defines.FOG) {
  37633. fallbacks.addFallback(1, "FOG");
  37634. }
  37635. if (defines.POINTSIZE) {
  37636. fallbacks.addFallback(0, "POINTSIZE");
  37637. }
  37638. if (defines.LOGARITHMICDEPTH) {
  37639. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  37640. }
  37641. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  37642. if (defines.SPECULARTERM) {
  37643. fallbacks.addFallback(0, "SPECULARTERM");
  37644. }
  37645. if (defines.NUM_BONE_INFLUENCERS > 0) {
  37646. fallbacks.addCPUSkinningFallback(0, mesh);
  37647. }
  37648. //Attributes
  37649. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37650. if (defines.NORMAL) {
  37651. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37652. }
  37653. if (defines.TANGENT) {
  37654. attribs.push(BABYLON.VertexBuffer.TangentKind);
  37655. }
  37656. if (defines.UV1) {
  37657. attribs.push(BABYLON.VertexBuffer.UVKind);
  37658. }
  37659. if (defines.UV2) {
  37660. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37661. }
  37662. if (defines.VERTEXCOLOR) {
  37663. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37664. }
  37665. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37666. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37667. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37668. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  37669. "vFogInfos", "vFogColor", "pointSize",
  37670. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37671. "mBones",
  37672. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37673. "vLightingIntensity",
  37674. "logarithmicDepthConstant",
  37675. "vSphericalX", "vSphericalY", "vSphericalZ",
  37676. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  37677. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  37678. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  37679. "vNormalReoderParams"
  37680. ];
  37681. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  37682. "bumpSampler", "lightmapSampler", "opacitySampler",
  37683. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  37684. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  37685. "microSurfaceSampler", "environmentBrdfSampler"];
  37686. var uniformBuffers = ["Material", "Scene"];
  37687. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37688. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37689. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37690. uniformsNames: uniforms,
  37691. uniformBuffersNames: uniformBuffers,
  37692. samplers: samplers,
  37693. defines: defines,
  37694. maxSimultaneousLights: this._maxSimultaneousLights
  37695. });
  37696. var onCompiled = function (effect) {
  37697. if (this.onCompiled) {
  37698. this.onCompiled(effect);
  37699. }
  37700. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  37701. }.bind(this);
  37702. var join = defines.toString();
  37703. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  37704. attributes: attribs,
  37705. uniformsNames: uniforms,
  37706. uniformBuffersNames: uniformBuffers,
  37707. samplers: samplers,
  37708. defines: join,
  37709. fallbacks: fallbacks,
  37710. onCompiled: onCompiled,
  37711. onError: this.onError,
  37712. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37713. }, engine), defines);
  37714. this.buildUniformLayout();
  37715. }
  37716. if (!subMesh.effect.isReady()) {
  37717. return false;
  37718. }
  37719. defines._renderId = scene.getRenderId();
  37720. this._wasPreviouslyReady = true;
  37721. return true;
  37722. };
  37723. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  37724. // Order is important !
  37725. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  37726. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  37727. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37728. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37729. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37730. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  37731. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  37732. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37733. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37734. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37735. this._uniformBuffer.addUniform("albedoMatrix", 16);
  37736. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37737. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37738. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37739. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37740. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  37741. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  37742. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37743. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  37744. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37745. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37746. this._uniformBuffer.addUniform("vReflectionColor", 3);
  37747. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  37748. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  37749. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  37750. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  37751. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  37752. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37753. this._uniformBuffer.addUniform("pointSize", 1);
  37754. this._uniformBuffer.create();
  37755. };
  37756. PBRBaseMaterial.prototype.unbind = function () {
  37757. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37758. this._uniformBuffer.setTexture("reflectionSampler", null);
  37759. }
  37760. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37761. this._uniformBuffer.setTexture("refractionSampler", null);
  37762. }
  37763. _super.prototype.unbind.call(this);
  37764. };
  37765. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37766. this._activeEffect.setMatrix("world", world);
  37767. };
  37768. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37769. var scene = this.getScene();
  37770. var defines = subMesh._materialDefines;
  37771. if (!defines) {
  37772. return;
  37773. }
  37774. var effect = subMesh.effect;
  37775. this._activeEffect = effect;
  37776. // Matrices
  37777. this.bindOnlyWorldMatrix(world);
  37778. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37779. // Bones
  37780. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37781. if (mustRebind) {
  37782. this._uniformBuffer.bindToEffect(effect, "Material");
  37783. this.bindViewProjection(effect);
  37784. var reflectionTexture = this._getReflectionTexture();
  37785. var refractionTexture = this._getRefractionTexture();
  37786. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37787. // Texture uniforms
  37788. if (scene.texturesEnabled) {
  37789. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37790. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37791. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37792. }
  37793. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37794. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37795. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37796. }
  37797. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37798. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37799. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37800. }
  37801. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37802. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37803. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37804. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  37805. var polynomials = reflectionTexture.sphericalPolynomial;
  37806. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37807. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37808. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37809. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37810. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37811. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37812. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37813. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37814. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37815. }
  37816. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37817. }
  37818. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37819. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37820. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37821. }
  37822. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37823. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37824. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37825. }
  37826. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37827. if (this._metallicTexture) {
  37828. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37829. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37830. }
  37831. else if (this._reflectivityTexture) {
  37832. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37833. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37834. }
  37835. if (this._microSurfaceTexture) {
  37836. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37837. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37838. }
  37839. }
  37840. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37841. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37842. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37843. if (scene._mirroredCameraPosition) {
  37844. 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);
  37845. }
  37846. else {
  37847. 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);
  37848. }
  37849. }
  37850. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37851. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37852. var depth = 1.0;
  37853. if (!refractionTexture.isCube) {
  37854. if (refractionTexture.depth) {
  37855. depth = refractionTexture.depth;
  37856. }
  37857. }
  37858. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37859. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37860. }
  37861. }
  37862. // Point size
  37863. if (this.pointsCloud) {
  37864. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37865. }
  37866. // Colors
  37867. if (defines.METALLICWORKFLOW) {
  37868. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37869. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37870. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37871. }
  37872. else {
  37873. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37874. }
  37875. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37876. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37877. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37878. // Misc
  37879. this._lightingInfos.x = this._directIntensity;
  37880. this._lightingInfos.y = this._emissiveIntensity;
  37881. this._lightingInfos.z = this._environmentIntensity;
  37882. this._lightingInfos.w = this._specularIntensity;
  37883. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37884. }
  37885. // Textures
  37886. if (scene.texturesEnabled) {
  37887. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37888. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37889. }
  37890. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37891. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37892. }
  37893. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37894. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37895. }
  37896. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37897. if (defines.LODBASEDMICROSFURACE) {
  37898. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37899. }
  37900. else {
  37901. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37902. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37903. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37904. }
  37905. }
  37906. if (defines.ENVIRONMENTBRDF) {
  37907. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37908. }
  37909. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37910. if (defines.LODBASEDMICROSFURACE) {
  37911. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37912. }
  37913. else {
  37914. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37915. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37916. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37917. }
  37918. }
  37919. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37920. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37921. }
  37922. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37923. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37924. }
  37925. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37926. if (this._metallicTexture) {
  37927. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37928. }
  37929. else if (this._reflectivityTexture) {
  37930. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37931. }
  37932. if (this._microSurfaceTexture) {
  37933. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37934. }
  37935. }
  37936. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37937. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37938. }
  37939. }
  37940. // Clip plane
  37941. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37942. // Colors
  37943. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37944. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  37945. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  37946. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37947. }
  37948. if (mustRebind || !this.isFrozen) {
  37949. // Lights
  37950. if (scene.lightsEnabled && !this._disableLighting) {
  37951. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37952. }
  37953. // View
  37954. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37955. this.bindView(effect);
  37956. }
  37957. // Fog
  37958. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37959. // Morph targets
  37960. if (defines.NUM_MORPH_INFLUENCERS) {
  37961. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37962. }
  37963. // image processing
  37964. this._imageProcessingConfiguration.bind(this._activeEffect);
  37965. // Log. depth
  37966. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37967. }
  37968. this._uniformBuffer.update();
  37969. this._afterBind(mesh);
  37970. scene = null;
  37971. };
  37972. PBRBaseMaterial.prototype.getAnimatables = function () {
  37973. var results = [];
  37974. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37975. results.push(this._albedoTexture);
  37976. }
  37977. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37978. results.push(this._ambientTexture);
  37979. }
  37980. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37981. results.push(this._opacityTexture);
  37982. }
  37983. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37984. results.push(this._reflectionTexture);
  37985. }
  37986. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37987. results.push(this._emissiveTexture);
  37988. }
  37989. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37990. results.push(this._metallicTexture);
  37991. }
  37992. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37993. results.push(this._reflectivityTexture);
  37994. }
  37995. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37996. results.push(this._bumpTexture);
  37997. }
  37998. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37999. results.push(this._lightmapTexture);
  38000. }
  38001. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  38002. results.push(this._refractionTexture);
  38003. }
  38004. return results;
  38005. };
  38006. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  38007. if (this._reflectionTexture) {
  38008. return this._reflectionTexture;
  38009. }
  38010. return this.getScene().environmentTexture;
  38011. };
  38012. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  38013. if (this._refractionTexture) {
  38014. return this._refractionTexture;
  38015. }
  38016. if (this._linkRefractionWithTransparency) {
  38017. return this.getScene().environmentTexture;
  38018. }
  38019. return null;
  38020. };
  38021. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38022. if (forceDisposeTextures) {
  38023. if (this._albedoTexture) {
  38024. this._albedoTexture.dispose();
  38025. }
  38026. if (this._ambientTexture) {
  38027. this._ambientTexture.dispose();
  38028. }
  38029. if (this._opacityTexture) {
  38030. this._opacityTexture.dispose();
  38031. }
  38032. if (this._reflectionTexture) {
  38033. this._reflectionTexture.dispose();
  38034. }
  38035. if (this._environmentBRDFTexture) {
  38036. this._environmentBRDFTexture.dispose();
  38037. }
  38038. if (this._emissiveTexture) {
  38039. this._emissiveTexture.dispose();
  38040. }
  38041. if (this._metallicTexture) {
  38042. this._metallicTexture.dispose();
  38043. }
  38044. if (this._reflectivityTexture) {
  38045. this._reflectivityTexture.dispose();
  38046. }
  38047. if (this._bumpTexture) {
  38048. this._bumpTexture.dispose();
  38049. }
  38050. if (this._lightmapTexture) {
  38051. this._lightmapTexture.dispose();
  38052. }
  38053. if (this._refractionTexture) {
  38054. this._refractionTexture.dispose();
  38055. }
  38056. }
  38057. this._renderTargets.dispose();
  38058. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38059. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38060. }
  38061. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38062. };
  38063. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  38064. __decorate([
  38065. BABYLON.serializeAsImageProcessingConfiguration()
  38066. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  38067. __decorate([
  38068. BABYLON.serialize()
  38069. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  38070. return PBRBaseMaterial;
  38071. }(BABYLON.PushMaterial));
  38072. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  38073. })(BABYLON || (BABYLON = {}));
  38074. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  38075. var BABYLON;
  38076. (function (BABYLON) {
  38077. var Internals;
  38078. (function (Internals) {
  38079. /**
  38080. * The Physically based simple base material of BJS.
  38081. *
  38082. * This enables better naming and convention enforcements on top of the pbrMaterial.
  38083. * It is used as the base class for both the specGloss and metalRough conventions.
  38084. */
  38085. var PBRBaseSimpleMaterial = (function (_super) {
  38086. __extends(PBRBaseSimpleMaterial, _super);
  38087. /**
  38088. * Instantiates a new PBRMaterial instance.
  38089. *
  38090. * @param name The material name
  38091. * @param scene The scene the material will be use in.
  38092. */
  38093. function PBRBaseSimpleMaterial(name, scene) {
  38094. var _this = _super.call(this, name, scene) || this;
  38095. /**
  38096. * Number of Simultaneous lights allowed on the material.
  38097. */
  38098. _this.maxSimultaneousLights = 4;
  38099. /**
  38100. * If sets to true, disables all the lights affecting the material.
  38101. */
  38102. _this.disableLighting = false;
  38103. /**
  38104. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38105. */
  38106. _this.invertNormalMapX = false;
  38107. /**
  38108. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38109. */
  38110. _this.invertNormalMapY = false;
  38111. /**
  38112. * Emissivie color used to self-illuminate the model.
  38113. */
  38114. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38115. /**
  38116. * Occlusion Channel Strenght.
  38117. */
  38118. _this.occlusionStrength = 1.0;
  38119. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38120. _this._useAmbientInGrayScale = true;
  38121. return _this;
  38122. }
  38123. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  38124. /**
  38125. * Gets the current transparency mode.
  38126. */
  38127. get: function () {
  38128. return this._transparencyMode;
  38129. },
  38130. /**
  38131. * Sets the transparency mode of the material.
  38132. */
  38133. set: function (value) {
  38134. if (this._transparencyMode === value) {
  38135. return;
  38136. }
  38137. this._transparencyMode = value;
  38138. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  38139. this._forceAlphaTest = true;
  38140. }
  38141. else {
  38142. this._forceAlphaTest = false;
  38143. }
  38144. this._markAllSubMeshesAsTexturesDirty();
  38145. },
  38146. enumerable: true,
  38147. configurable: true
  38148. });
  38149. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  38150. /**
  38151. * Gets the current double sided mode.
  38152. */
  38153. get: function () {
  38154. return this._twoSidedLighting;
  38155. },
  38156. /**
  38157. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38158. */
  38159. set: function (value) {
  38160. if (this._twoSidedLighting === value) {
  38161. return;
  38162. }
  38163. this._twoSidedLighting = value;
  38164. this.backFaceCulling = !value;
  38165. this._markAllSubMeshesAsTexturesDirty();
  38166. },
  38167. enumerable: true,
  38168. configurable: true
  38169. });
  38170. /**
  38171. * Specifies wether or not the alpha value of the albedo texture should be used.
  38172. */
  38173. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38174. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38175. };
  38176. /**
  38177. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  38178. */
  38179. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  38180. if (this._linkRefractionWithTransparency) {
  38181. return false;
  38182. }
  38183. return (this.alpha < 1.0) ||
  38184. (this._shouldUseAlphaFromAlbedoTexture() &&
  38185. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  38186. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  38187. };
  38188. /**
  38189. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  38190. */
  38191. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  38192. if (this._linkRefractionWithTransparency) {
  38193. return false;
  38194. }
  38195. return this._shouldUseAlphaFromAlbedoTexture() &&
  38196. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  38197. };
  38198. /**
  38199. * Return the active textures of the material.
  38200. */
  38201. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  38202. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38203. if (this.environmentTexture) {
  38204. activeTextures.push(this.environmentTexture);
  38205. }
  38206. if (this.normalTexture) {
  38207. activeTextures.push(this.normalTexture);
  38208. }
  38209. if (this.emissiveTexture) {
  38210. activeTextures.push(this.emissiveTexture);
  38211. }
  38212. if (this.occlusionTexture) {
  38213. activeTextures.push(this.occlusionTexture);
  38214. }
  38215. return activeTextures;
  38216. };
  38217. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  38218. return "PBRBaseSimpleMaterial";
  38219. };
  38220. __decorate([
  38221. BABYLON.serialize(),
  38222. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38223. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  38224. __decorate([
  38225. BABYLON.serialize(),
  38226. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38227. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  38228. __decorate([
  38229. BABYLON.serializeAsTexture(),
  38230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  38231. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  38232. __decorate([
  38233. BABYLON.serialize(),
  38234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38235. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  38236. __decorate([
  38237. BABYLON.serialize(),
  38238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38239. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  38240. __decorate([
  38241. BABYLON.serializeAsTexture(),
  38242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  38243. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  38244. __decorate([
  38245. BABYLON.serializeAsColor3("emissive"),
  38246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38247. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  38248. __decorate([
  38249. BABYLON.serializeAsTexture(),
  38250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38251. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  38252. __decorate([
  38253. BABYLON.serialize(),
  38254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  38255. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  38256. __decorate([
  38257. BABYLON.serializeAsTexture(),
  38258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  38259. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  38260. __decorate([
  38261. BABYLON.serialize(),
  38262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  38263. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  38264. __decorate([
  38265. BABYLON.serialize()
  38266. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  38267. __decorate([
  38268. BABYLON.serialize()
  38269. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  38270. return PBRBaseSimpleMaterial;
  38271. }(BABYLON.PBRBaseMaterial));
  38272. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  38273. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38274. })(BABYLON || (BABYLON = {}));
  38275. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  38276. var BABYLON;
  38277. (function (BABYLON) {
  38278. /**
  38279. * The Physically based material of BJS.
  38280. *
  38281. * This offers the main features of a standard PBR material.
  38282. * For more information, please refer to the documentation :
  38283. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38284. */
  38285. var PBRMaterial = (function (_super) {
  38286. __extends(PBRMaterial, _super);
  38287. /**
  38288. * Instantiates a new PBRMaterial instance.
  38289. *
  38290. * @param name The material name
  38291. * @param scene The scene the material will be use in.
  38292. */
  38293. function PBRMaterial(name, scene) {
  38294. var _this = _super.call(this, name, scene) || this;
  38295. /**
  38296. * Intensity of the direct lights e.g. the four lights available in your scene.
  38297. * This impacts both the direct diffuse and specular highlights.
  38298. */
  38299. _this.directIntensity = 1.0;
  38300. /**
  38301. * Intensity of the emissive part of the material.
  38302. * This helps controlling the emissive effect without modifying the emissive color.
  38303. */
  38304. _this.emissiveIntensity = 1.0;
  38305. /**
  38306. * Intensity of the environment e.g. how much the environment will light the object
  38307. * either through harmonics for rough material or through the refelction for shiny ones.
  38308. */
  38309. _this.environmentIntensity = 1.0;
  38310. /**
  38311. * This is a special control allowing the reduction of the specular highlights coming from the
  38312. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38313. */
  38314. _this.specularIntensity = 1.0;
  38315. /**
  38316. * Debug Control allowing disabling the bump map on this material.
  38317. */
  38318. _this.disableBumpMap = false;
  38319. /**
  38320. * AKA Occlusion Texture Intensity in other nomenclature.
  38321. */
  38322. _this.ambientTextureStrength = 1.0;
  38323. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38324. /**
  38325. * AKA Diffuse Color in other nomenclature.
  38326. */
  38327. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  38328. /**
  38329. * AKA Specular Color in other nomenclature.
  38330. */
  38331. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38332. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  38333. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38334. /**
  38335. * AKA Glossiness in other nomenclature.
  38336. */
  38337. _this.microSurface = 1.0;
  38338. /**
  38339. * source material index of refraction (IOR)' / 'destination material IOR.
  38340. */
  38341. _this.indexOfRefraction = 0.66;
  38342. /**
  38343. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38344. */
  38345. _this.invertRefractionY = false;
  38346. /**
  38347. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38348. * Materials half opaque for instance using refraction could benefit from this control.
  38349. */
  38350. _this.linkRefractionWithTransparency = false;
  38351. _this.useLightmapAsShadowmap = false;
  38352. /**
  38353. * Specifies that the alpha is coming form the albedo channel alpha channel.
  38354. */
  38355. _this.useAlphaFromAlbedoTexture = false;
  38356. /**
  38357. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38358. */
  38359. _this.forceAlphaTest = false;
  38360. /**
  38361. * Defines the alpha limits in alpha test mode.
  38362. */
  38363. _this.alphaCutOff = 0.4;
  38364. /**
  38365. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38366. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38367. */
  38368. _this.useSpecularOverAlpha = true;
  38369. /**
  38370. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38371. */
  38372. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  38373. /**
  38374. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38375. */
  38376. _this.useRoughnessFromMetallicTextureAlpha = true;
  38377. /**
  38378. * Specifies if the metallic texture contains the roughness information in its green channel.
  38379. */
  38380. _this.useRoughnessFromMetallicTextureGreen = false;
  38381. /**
  38382. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38383. */
  38384. _this.useMetallnessFromMetallicTextureBlue = false;
  38385. /**
  38386. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38387. */
  38388. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  38389. /**
  38390. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38391. */
  38392. _this.useAmbientInGrayScale = false;
  38393. /**
  38394. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38395. * The material will try to infer what glossiness each pixel should be.
  38396. */
  38397. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  38398. /**
  38399. * BJS is using an harcoded light falloff based on a manually sets up range.
  38400. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38401. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38402. */
  38403. _this.usePhysicalLightFalloff = true;
  38404. /**
  38405. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38406. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38407. */
  38408. _this.useRadianceOverAlpha = true;
  38409. /**
  38410. * Allows using the bump map in parallax mode.
  38411. */
  38412. _this.useParallax = false;
  38413. /**
  38414. * Allows using the bump map in parallax occlusion mode.
  38415. */
  38416. _this.useParallaxOcclusion = false;
  38417. /**
  38418. * Controls the scale bias of the parallax mode.
  38419. */
  38420. _this.parallaxScaleBias = 0.05;
  38421. /**
  38422. * If sets to true, disables all the lights affecting the material.
  38423. */
  38424. _this.disableLighting = false;
  38425. /**
  38426. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38427. */
  38428. _this.forceIrradianceInFragment = false;
  38429. /**
  38430. * Number of Simultaneous lights allowed on the material.
  38431. */
  38432. _this.maxSimultaneousLights = 4;
  38433. /**
  38434. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38435. */
  38436. _this.invertNormalMapX = false;
  38437. /**
  38438. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38439. */
  38440. _this.invertNormalMapY = false;
  38441. /**
  38442. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38443. */
  38444. _this.twoSidedLighting = false;
  38445. /**
  38446. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  38447. * in your scene composition.
  38448. */
  38449. _this.preMultiplyAlpha = false;
  38450. /**
  38451. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38452. * And/Or occlude the blended part.
  38453. */
  38454. _this.useAlphaFresnel = false;
  38455. /**
  38456. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38457. * And/Or occlude the blended part.
  38458. */
  38459. _this.environmentBRDFTexture = null;
  38460. /**
  38461. * Force normal to face away from face.
  38462. * (Temporary internal fix to remove before 3.1)
  38463. */
  38464. _this.forceNormalForward = false;
  38465. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38466. return _this;
  38467. }
  38468. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  38469. /**
  38470. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  38471. */
  38472. get: function () {
  38473. return this._PBRMATERIAL_OPAQUE;
  38474. },
  38475. enumerable: true,
  38476. configurable: true
  38477. });
  38478. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  38479. /**
  38480. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  38481. */
  38482. get: function () {
  38483. return this._PBRMATERIAL_ALPHATEST;
  38484. },
  38485. enumerable: true,
  38486. configurable: true
  38487. });
  38488. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  38489. /**
  38490. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38491. */
  38492. get: function () {
  38493. return this._PBRMATERIAL_ALPHABLEND;
  38494. },
  38495. enumerable: true,
  38496. configurable: true
  38497. });
  38498. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  38499. /**
  38500. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38501. * They are also discarded below the alpha cutoff threshold to improve performances.
  38502. */
  38503. get: function () {
  38504. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  38505. },
  38506. enumerable: true,
  38507. configurable: true
  38508. });
  38509. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  38510. /**
  38511. * Gets the image processing configuration used either in this material.
  38512. */
  38513. get: function () {
  38514. return this._imageProcessingConfiguration;
  38515. },
  38516. /**
  38517. * Sets the Default image processing configuration used either in the this material.
  38518. *
  38519. * If sets to null, the scene one is in use.
  38520. */
  38521. set: function (value) {
  38522. this._attachImageProcessingConfiguration(value);
  38523. // Ensure the effect will be rebuilt.
  38524. this._markAllSubMeshesAsTexturesDirty();
  38525. },
  38526. enumerable: true,
  38527. configurable: true
  38528. });
  38529. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  38530. /**
  38531. * Gets wether the color curves effect is enabled.
  38532. */
  38533. get: function () {
  38534. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38535. },
  38536. /**
  38537. * Sets wether the color curves effect is enabled.
  38538. */
  38539. set: function (value) {
  38540. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38541. },
  38542. enumerable: true,
  38543. configurable: true
  38544. });
  38545. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  38546. /**
  38547. * Gets wether the color grading effect is enabled.
  38548. */
  38549. get: function () {
  38550. return this.imageProcessingConfiguration.colorGradingEnabled;
  38551. },
  38552. /**
  38553. * Gets wether the color grading effect is enabled.
  38554. */
  38555. set: function (value) {
  38556. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38557. },
  38558. enumerable: true,
  38559. configurable: true
  38560. });
  38561. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  38562. /**
  38563. * Gets wether tonemapping is enabled or not.
  38564. */
  38565. get: function () {
  38566. return this._imageProcessingConfiguration.toneMappingEnabled;
  38567. },
  38568. /**
  38569. * Sets wether tonemapping is enabled or not
  38570. */
  38571. set: function (value) {
  38572. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38573. },
  38574. enumerable: true,
  38575. configurable: true
  38576. });
  38577. ;
  38578. ;
  38579. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  38580. /**
  38581. * The camera exposure used on this material.
  38582. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38583. * This corresponds to a photographic exposure.
  38584. */
  38585. get: function () {
  38586. return this._imageProcessingConfiguration.exposure;
  38587. },
  38588. /**
  38589. * The camera exposure used on this material.
  38590. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38591. * This corresponds to a photographic exposure.
  38592. */
  38593. set: function (value) {
  38594. this._imageProcessingConfiguration.exposure = value;
  38595. },
  38596. enumerable: true,
  38597. configurable: true
  38598. });
  38599. ;
  38600. ;
  38601. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  38602. /**
  38603. * Gets The camera contrast used on this material.
  38604. */
  38605. get: function () {
  38606. return this._imageProcessingConfiguration.contrast;
  38607. },
  38608. /**
  38609. * Sets The camera contrast used on this material.
  38610. */
  38611. set: function (value) {
  38612. this._imageProcessingConfiguration.contrast = value;
  38613. },
  38614. enumerable: true,
  38615. configurable: true
  38616. });
  38617. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  38618. /**
  38619. * Gets the Color Grading 2D Lookup Texture.
  38620. */
  38621. get: function () {
  38622. return this._imageProcessingConfiguration.colorGradingTexture;
  38623. },
  38624. /**
  38625. * Sets the Color Grading 2D Lookup Texture.
  38626. */
  38627. set: function (value) {
  38628. this._imageProcessingConfiguration.colorGradingTexture = value;
  38629. },
  38630. enumerable: true,
  38631. configurable: true
  38632. });
  38633. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  38634. /**
  38635. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38636. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38637. * 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;
  38638. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38639. */
  38640. get: function () {
  38641. return this._imageProcessingConfiguration.colorCurves;
  38642. },
  38643. /**
  38644. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38645. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38646. * 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;
  38647. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38648. */
  38649. set: function (value) {
  38650. this._imageProcessingConfiguration.colorCurves = value;
  38651. },
  38652. enumerable: true,
  38653. configurable: true
  38654. });
  38655. PBRMaterial.prototype.getClassName = function () {
  38656. return "PBRMaterial";
  38657. };
  38658. PBRMaterial.prototype.getActiveTextures = function () {
  38659. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38660. if (this._albedoTexture) {
  38661. activeTextures.push(this._albedoTexture);
  38662. }
  38663. if (this._ambientTexture) {
  38664. activeTextures.push(this._ambientTexture);
  38665. }
  38666. if (this._opacityTexture) {
  38667. activeTextures.push(this._opacityTexture);
  38668. }
  38669. if (this._reflectionTexture) {
  38670. activeTextures.push(this._reflectionTexture);
  38671. }
  38672. if (this._emissiveTexture) {
  38673. activeTextures.push(this._emissiveTexture);
  38674. }
  38675. if (this._reflectivityTexture) {
  38676. activeTextures.push(this._reflectivityTexture);
  38677. }
  38678. if (this._metallicTexture) {
  38679. activeTextures.push(this._metallicTexture);
  38680. }
  38681. if (this._microSurfaceTexture) {
  38682. activeTextures.push(this._microSurfaceTexture);
  38683. }
  38684. if (this._bumpTexture) {
  38685. activeTextures.push(this._bumpTexture);
  38686. }
  38687. if (this._lightmapTexture) {
  38688. activeTextures.push(this._lightmapTexture);
  38689. }
  38690. if (this._refractionTexture) {
  38691. activeTextures.push(this._refractionTexture);
  38692. }
  38693. return activeTextures;
  38694. };
  38695. PBRMaterial.prototype.hasTexture = function (texture) {
  38696. if (_super.prototype.hasTexture.call(this, texture)) {
  38697. return true;
  38698. }
  38699. if (this._albedoTexture === texture) {
  38700. return true;
  38701. }
  38702. if (this._ambientTexture === texture) {
  38703. return true;
  38704. }
  38705. if (this._opacityTexture === texture) {
  38706. return true;
  38707. }
  38708. if (this._reflectionTexture === texture) {
  38709. return true;
  38710. }
  38711. if (this._reflectivityTexture === texture) {
  38712. return true;
  38713. }
  38714. if (this._metallicTexture === texture) {
  38715. return true;
  38716. }
  38717. if (this._microSurfaceTexture === texture) {
  38718. return true;
  38719. }
  38720. if (this._bumpTexture === texture) {
  38721. return true;
  38722. }
  38723. if (this._lightmapTexture === texture) {
  38724. return true;
  38725. }
  38726. if (this._refractionTexture === texture) {
  38727. return true;
  38728. }
  38729. return false;
  38730. };
  38731. PBRMaterial.prototype.clone = function (name) {
  38732. var _this = this;
  38733. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  38734. };
  38735. PBRMaterial.prototype.serialize = function () {
  38736. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38737. serializationObject.customType = "BABYLON.PBRMaterial";
  38738. return serializationObject;
  38739. };
  38740. // Statics
  38741. PBRMaterial.Parse = function (source, scene, rootUrl) {
  38742. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  38743. };
  38744. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  38745. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  38746. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  38747. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  38748. __decorate([
  38749. BABYLON.serialize(),
  38750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38751. ], PBRMaterial.prototype, "directIntensity", void 0);
  38752. __decorate([
  38753. BABYLON.serialize(),
  38754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38755. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  38756. __decorate([
  38757. BABYLON.serialize(),
  38758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38759. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  38760. __decorate([
  38761. BABYLON.serialize(),
  38762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38763. ], PBRMaterial.prototype, "specularIntensity", void 0);
  38764. __decorate([
  38765. BABYLON.serialize(),
  38766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38767. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  38768. __decorate([
  38769. BABYLON.serializeAsTexture(),
  38770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38771. ], PBRMaterial.prototype, "albedoTexture", void 0);
  38772. __decorate([
  38773. BABYLON.serializeAsTexture(),
  38774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38775. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38776. __decorate([
  38777. BABYLON.serialize(),
  38778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38779. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38780. __decorate([
  38781. BABYLON.serializeAsTexture(),
  38782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38783. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38784. __decorate([
  38785. BABYLON.serializeAsTexture(),
  38786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38787. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38788. __decorate([
  38789. BABYLON.serializeAsTexture(),
  38790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38791. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38792. __decorate([
  38793. BABYLON.serializeAsTexture(),
  38794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38795. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38796. __decorate([
  38797. BABYLON.serializeAsTexture(),
  38798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38799. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38800. __decorate([
  38801. BABYLON.serialize(),
  38802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38803. ], PBRMaterial.prototype, "metallic", void 0);
  38804. __decorate([
  38805. BABYLON.serialize(),
  38806. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38807. ], PBRMaterial.prototype, "roughness", void 0);
  38808. __decorate([
  38809. BABYLON.serializeAsTexture(),
  38810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38811. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38812. __decorate([
  38813. BABYLON.serializeAsTexture(),
  38814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38815. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38816. __decorate([
  38817. BABYLON.serializeAsTexture(),
  38818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38819. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38820. __decorate([
  38821. BABYLON.serializeAsTexture(),
  38822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38823. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38824. __decorate([
  38825. BABYLON.serializeAsColor3("ambient"),
  38826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38827. ], PBRMaterial.prototype, "ambientColor", void 0);
  38828. __decorate([
  38829. BABYLON.serializeAsColor3("albedo"),
  38830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38831. ], PBRMaterial.prototype, "albedoColor", void 0);
  38832. __decorate([
  38833. BABYLON.serializeAsColor3("reflectivity"),
  38834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38835. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38836. __decorate([
  38837. BABYLON.serializeAsColor3("reflection"),
  38838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38839. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38840. __decorate([
  38841. BABYLON.serializeAsColor3("emissive"),
  38842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38843. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38844. __decorate([
  38845. BABYLON.serialize(),
  38846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38847. ], PBRMaterial.prototype, "microSurface", void 0);
  38848. __decorate([
  38849. BABYLON.serialize(),
  38850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38851. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38852. __decorate([
  38853. BABYLON.serialize(),
  38854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38855. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38856. __decorate([
  38857. BABYLON.serialize(),
  38858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38859. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38860. __decorate([
  38861. BABYLON.serialize(),
  38862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38863. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38864. __decorate([
  38865. BABYLON.serialize(),
  38866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38867. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38868. __decorate([
  38869. BABYLON.serialize(),
  38870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38871. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38872. __decorate([
  38873. BABYLON.serialize(),
  38874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38875. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38876. __decorate([
  38877. BABYLON.serialize(),
  38878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38879. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38880. __decorate([
  38881. BABYLON.serialize(),
  38882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38883. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38884. __decorate([
  38885. BABYLON.serialize(),
  38886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38887. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38888. __decorate([
  38889. BABYLON.serialize(),
  38890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38891. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38892. __decorate([
  38893. BABYLON.serialize(),
  38894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38895. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38896. __decorate([
  38897. BABYLON.serialize(),
  38898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38899. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38900. __decorate([
  38901. BABYLON.serialize(),
  38902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38903. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38904. __decorate([
  38905. BABYLON.serialize(),
  38906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38907. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38908. __decorate([
  38909. BABYLON.serialize(),
  38910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38911. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38912. __decorate([
  38913. BABYLON.serialize(),
  38914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38915. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38916. __decorate([
  38917. BABYLON.serialize(),
  38918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38919. ], PBRMaterial.prototype, "useParallax", void 0);
  38920. __decorate([
  38921. BABYLON.serialize(),
  38922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38923. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38924. __decorate([
  38925. BABYLON.serialize(),
  38926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38927. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38928. __decorate([
  38929. BABYLON.serialize(),
  38930. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38931. ], PBRMaterial.prototype, "disableLighting", void 0);
  38932. __decorate([
  38933. BABYLON.serialize(),
  38934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38935. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38936. __decorate([
  38937. BABYLON.serialize(),
  38938. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38939. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38940. __decorate([
  38941. BABYLON.serialize(),
  38942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38943. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38944. __decorate([
  38945. BABYLON.serialize(),
  38946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38947. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38948. __decorate([
  38949. BABYLON.serialize(),
  38950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38951. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38952. __decorate([
  38953. BABYLON.serialize(),
  38954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38955. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  38956. __decorate([
  38957. BABYLON.serialize(),
  38958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38959. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38960. __decorate([
  38961. BABYLON.serializeAsTexture(),
  38962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38963. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38964. __decorate([
  38965. BABYLON.serialize(),
  38966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38967. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38968. return PBRMaterial;
  38969. }(BABYLON.PBRBaseMaterial));
  38970. BABYLON.PBRMaterial = PBRMaterial;
  38971. })(BABYLON || (BABYLON = {}));
  38972. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38973. var BABYLON;
  38974. (function (BABYLON) {
  38975. /**
  38976. * The PBR material of BJS following the metal roughness convention.
  38977. *
  38978. * This fits to the PBR convention in the GLTF definition:
  38979. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38980. */
  38981. var PBRMetallicRoughnessMaterial = (function (_super) {
  38982. __extends(PBRMetallicRoughnessMaterial, _super);
  38983. /**
  38984. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38985. *
  38986. * @param name The material name
  38987. * @param scene The scene the material will be use in.
  38988. */
  38989. function PBRMetallicRoughnessMaterial(name, scene) {
  38990. var _this = _super.call(this, name, scene) || this;
  38991. _this._useRoughnessFromMetallicTextureAlpha = false;
  38992. _this._useRoughnessFromMetallicTextureGreen = true;
  38993. _this._useMetallnessFromMetallicTextureBlue = true;
  38994. return _this;
  38995. }
  38996. /**
  38997. * Return the currrent class name of the material.
  38998. */
  38999. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  39000. return "PBRMetallicRoughnessMaterial";
  39001. };
  39002. /**
  39003. * Return the active textures of the material.
  39004. */
  39005. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  39006. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39007. if (this.baseTexture) {
  39008. activeTextures.push(this.baseTexture);
  39009. }
  39010. if (this.metallicRoughnessTexture) {
  39011. activeTextures.push(this.metallicRoughnessTexture);
  39012. }
  39013. return activeTextures;
  39014. };
  39015. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  39016. if (_super.prototype.hasTexture.call(this, texture)) {
  39017. return true;
  39018. }
  39019. if (this.baseTexture === texture) {
  39020. return true;
  39021. }
  39022. if (this.metallicRoughnessTexture === texture) {
  39023. return true;
  39024. }
  39025. return false;
  39026. };
  39027. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  39028. var _this = this;
  39029. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  39030. };
  39031. /**
  39032. * Serialize the material to a parsable JSON object.
  39033. */
  39034. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  39035. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39036. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  39037. return serializationObject;
  39038. };
  39039. /**
  39040. * Parses a JSON object correponding to the serialize function.
  39041. */
  39042. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  39043. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  39044. };
  39045. __decorate([
  39046. BABYLON.serializeAsColor3(),
  39047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39048. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  39049. __decorate([
  39050. BABYLON.serializeAsTexture(),
  39051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39052. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  39053. __decorate([
  39054. BABYLON.serialize(),
  39055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39056. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  39057. __decorate([
  39058. BABYLON.serialize(),
  39059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39060. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  39061. __decorate([
  39062. BABYLON.serializeAsTexture(),
  39063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  39064. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  39065. return PBRMetallicRoughnessMaterial;
  39066. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  39067. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  39068. })(BABYLON || (BABYLON = {}));
  39069. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  39070. var BABYLON;
  39071. (function (BABYLON) {
  39072. /**
  39073. * The PBR material of BJS following the specular glossiness convention.
  39074. *
  39075. * This fits to the PBR convention in the GLTF definition:
  39076. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  39077. */
  39078. var PBRSpecularGlossinessMaterial = (function (_super) {
  39079. __extends(PBRSpecularGlossinessMaterial, _super);
  39080. /**
  39081. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  39082. *
  39083. * @param name The material name
  39084. * @param scene The scene the material will be use in.
  39085. */
  39086. function PBRSpecularGlossinessMaterial(name, scene) {
  39087. var _this = _super.call(this, name, scene) || this;
  39088. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  39089. return _this;
  39090. }
  39091. /**
  39092. * Return the currrent class name of the material.
  39093. */
  39094. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  39095. return "PBRSpecularGlossinessMaterial";
  39096. };
  39097. /**
  39098. * Return the active textures of the material.
  39099. */
  39100. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  39101. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39102. if (this.diffuseTexture) {
  39103. activeTextures.push(this.diffuseTexture);
  39104. }
  39105. if (this.specularGlossinessTexture) {
  39106. activeTextures.push(this.specularGlossinessTexture);
  39107. }
  39108. return activeTextures;
  39109. };
  39110. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  39111. if (_super.prototype.hasTexture.call(this, texture)) {
  39112. return true;
  39113. }
  39114. if (this.diffuseTexture === texture) {
  39115. return true;
  39116. }
  39117. if (this.specularGlossinessTexture === texture) {
  39118. return true;
  39119. }
  39120. return false;
  39121. };
  39122. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  39123. var _this = this;
  39124. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  39125. };
  39126. /**
  39127. * Serialize the material to a parsable JSON object.
  39128. */
  39129. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  39130. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39131. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  39132. return serializationObject;
  39133. };
  39134. /**
  39135. * Parses a JSON object correponding to the serialize function.
  39136. */
  39137. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  39138. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  39139. };
  39140. __decorate([
  39141. BABYLON.serializeAsColor3("diffuse"),
  39142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39143. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  39144. __decorate([
  39145. BABYLON.serializeAsTexture(),
  39146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39147. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  39148. __decorate([
  39149. BABYLON.serializeAsColor3("specular"),
  39150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  39151. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  39152. __decorate([
  39153. BABYLON.serialize(),
  39154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  39155. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  39156. __decorate([
  39157. BABYLON.serializeAsTexture(),
  39158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  39159. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  39160. return PBRSpecularGlossinessMaterial;
  39161. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  39162. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  39163. })(BABYLON || (BABYLON = {}));
  39164. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  39165. var BABYLON;
  39166. (function (BABYLON) {
  39167. var ShaderMaterial = (function (_super) {
  39168. __extends(ShaderMaterial, _super);
  39169. function ShaderMaterial(name, scene, shaderPath, options) {
  39170. var _this = _super.call(this, name, scene) || this;
  39171. _this._textures = {};
  39172. _this._textureArrays = {};
  39173. _this._floats = {};
  39174. _this._floatsArrays = {};
  39175. _this._colors3 = {};
  39176. _this._colors3Arrays = {};
  39177. _this._colors4 = {};
  39178. _this._vectors2 = {};
  39179. _this._vectors3 = {};
  39180. _this._vectors4 = {};
  39181. _this._matrices = {};
  39182. _this._matrices3x3 = {};
  39183. _this._matrices2x2 = {};
  39184. _this._vectors3Arrays = {};
  39185. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  39186. _this._shaderPath = shaderPath;
  39187. options.needAlphaBlending = options.needAlphaBlending || false;
  39188. options.needAlphaTesting = options.needAlphaTesting || false;
  39189. options.attributes = options.attributes || ["position", "normal", "uv"];
  39190. options.uniforms = options.uniforms || ["worldViewProjection"];
  39191. options.uniformBuffers = options.uniformBuffers || [];
  39192. options.samplers = options.samplers || [];
  39193. options.defines = options.defines || [];
  39194. _this._options = options;
  39195. return _this;
  39196. }
  39197. ShaderMaterial.prototype.getClassName = function () {
  39198. return "ShaderMaterial";
  39199. };
  39200. ShaderMaterial.prototype.needAlphaBlending = function () {
  39201. return this._options.needAlphaBlending;
  39202. };
  39203. ShaderMaterial.prototype.needAlphaTesting = function () {
  39204. return this._options.needAlphaTesting;
  39205. };
  39206. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  39207. if (this._options.uniforms.indexOf(uniformName) === -1) {
  39208. this._options.uniforms.push(uniformName);
  39209. }
  39210. };
  39211. ShaderMaterial.prototype.setTexture = function (name, texture) {
  39212. if (this._options.samplers.indexOf(name) === -1) {
  39213. this._options.samplers.push(name);
  39214. }
  39215. this._textures[name] = texture;
  39216. return this;
  39217. };
  39218. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  39219. if (this._options.samplers.indexOf(name) === -1) {
  39220. this._options.samplers.push(name);
  39221. }
  39222. this._checkUniform(name);
  39223. this._textureArrays[name] = textures;
  39224. return this;
  39225. };
  39226. ShaderMaterial.prototype.setFloat = function (name, value) {
  39227. this._checkUniform(name);
  39228. this._floats[name] = value;
  39229. return this;
  39230. };
  39231. ShaderMaterial.prototype.setFloats = function (name, value) {
  39232. this._checkUniform(name);
  39233. this._floatsArrays[name] = value;
  39234. return this;
  39235. };
  39236. ShaderMaterial.prototype.setColor3 = function (name, value) {
  39237. this._checkUniform(name);
  39238. this._colors3[name] = value;
  39239. return this;
  39240. };
  39241. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  39242. this._checkUniform(name);
  39243. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  39244. color.toArray(arr, arr.length);
  39245. return arr;
  39246. }, []);
  39247. return this;
  39248. };
  39249. ShaderMaterial.prototype.setColor4 = function (name, value) {
  39250. this._checkUniform(name);
  39251. this._colors4[name] = value;
  39252. return this;
  39253. };
  39254. ShaderMaterial.prototype.setVector2 = function (name, value) {
  39255. this._checkUniform(name);
  39256. this._vectors2[name] = value;
  39257. return this;
  39258. };
  39259. ShaderMaterial.prototype.setVector3 = function (name, value) {
  39260. this._checkUniform(name);
  39261. this._vectors3[name] = value;
  39262. return this;
  39263. };
  39264. ShaderMaterial.prototype.setVector4 = function (name, value) {
  39265. this._checkUniform(name);
  39266. this._vectors4[name] = value;
  39267. return this;
  39268. };
  39269. ShaderMaterial.prototype.setMatrix = function (name, value) {
  39270. this._checkUniform(name);
  39271. this._matrices[name] = value;
  39272. return this;
  39273. };
  39274. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  39275. this._checkUniform(name);
  39276. this._matrices3x3[name] = value;
  39277. return this;
  39278. };
  39279. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  39280. this._checkUniform(name);
  39281. this._matrices2x2[name] = value;
  39282. return this;
  39283. };
  39284. ShaderMaterial.prototype.setArray3 = function (name, value) {
  39285. this._checkUniform(name);
  39286. this._vectors3Arrays[name] = value;
  39287. return this;
  39288. };
  39289. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  39290. if (!mesh) {
  39291. return true;
  39292. }
  39293. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  39294. return false;
  39295. }
  39296. return false;
  39297. };
  39298. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  39299. var scene = this.getScene();
  39300. var engine = scene.getEngine();
  39301. if (!this.checkReadyOnEveryCall) {
  39302. if (this._renderId === scene.getRenderId()) {
  39303. if (this._checkCache(scene, mesh, useInstances)) {
  39304. return true;
  39305. }
  39306. }
  39307. }
  39308. // Instances
  39309. var defines = [];
  39310. var attribs = [];
  39311. var fallbacks = new BABYLON.EffectFallbacks();
  39312. if (useInstances) {
  39313. defines.push("#define INSTANCES");
  39314. }
  39315. for (var index = 0; index < this._options.defines.length; index++) {
  39316. defines.push(this._options.defines[index]);
  39317. }
  39318. for (var index = 0; index < this._options.attributes.length; index++) {
  39319. attribs.push(this._options.attributes[index]);
  39320. }
  39321. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39322. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39323. defines.push("#define VERTEXCOLOR");
  39324. }
  39325. // Bones
  39326. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  39327. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39328. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39329. if (mesh.numBoneInfluencers > 4) {
  39330. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39331. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39332. }
  39333. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39334. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39335. fallbacks.addCPUSkinningFallback(0, mesh);
  39336. if (this._options.uniforms.indexOf("mBones") === -1) {
  39337. this._options.uniforms.push("mBones");
  39338. }
  39339. }
  39340. else {
  39341. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39342. }
  39343. // Textures
  39344. for (var name in this._textures) {
  39345. if (!this._textures[name].isReady()) {
  39346. return false;
  39347. }
  39348. }
  39349. // Alpha test
  39350. if (engine.getAlphaTesting()) {
  39351. defines.push("#define ALPHATEST");
  39352. }
  39353. var previousEffect = this._effect;
  39354. var join = defines.join("\n");
  39355. this._effect = engine.createEffect(this._shaderPath, {
  39356. attributes: attribs,
  39357. uniformsNames: this._options.uniforms,
  39358. uniformBuffersNames: this._options.uniformBuffers,
  39359. samplers: this._options.samplers,
  39360. defines: join,
  39361. fallbacks: fallbacks,
  39362. onCompiled: this.onCompiled,
  39363. onError: this.onError
  39364. }, engine);
  39365. if (!this._effect.isReady()) {
  39366. return false;
  39367. }
  39368. if (previousEffect !== this._effect) {
  39369. scene.resetCachedMaterial();
  39370. }
  39371. this._renderId = scene.getRenderId();
  39372. return true;
  39373. };
  39374. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39375. var scene = this.getScene();
  39376. if (this._options.uniforms.indexOf("world") !== -1) {
  39377. this._effect.setMatrix("world", world);
  39378. }
  39379. if (this._options.uniforms.indexOf("worldView") !== -1) {
  39380. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  39381. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  39382. }
  39383. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  39384. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  39385. }
  39386. };
  39387. ShaderMaterial.prototype.bind = function (world, mesh) {
  39388. // Std values
  39389. this.bindOnlyWorldMatrix(world);
  39390. if (this.getScene().getCachedMaterial() !== this) {
  39391. if (this._options.uniforms.indexOf("view") !== -1) {
  39392. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  39393. }
  39394. if (this._options.uniforms.indexOf("projection") !== -1) {
  39395. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  39396. }
  39397. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  39398. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  39399. }
  39400. // Bones
  39401. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  39402. var name;
  39403. // Texture
  39404. for (name in this._textures) {
  39405. this._effect.setTexture(name, this._textures[name]);
  39406. }
  39407. // Texture arrays
  39408. for (name in this._textureArrays) {
  39409. this._effect.setTextureArray(name, this._textureArrays[name]);
  39410. }
  39411. // Float
  39412. for (name in this._floats) {
  39413. this._effect.setFloat(name, this._floats[name]);
  39414. }
  39415. // Float s
  39416. for (name in this._floatsArrays) {
  39417. this._effect.setArray(name, this._floatsArrays[name]);
  39418. }
  39419. // Color3
  39420. for (name in this._colors3) {
  39421. this._effect.setColor3(name, this._colors3[name]);
  39422. }
  39423. for (name in this._colors3Arrays) {
  39424. this._effect.setArray3(name, this._colors3Arrays[name]);
  39425. }
  39426. // Color4
  39427. for (name in this._colors4) {
  39428. var color = this._colors4[name];
  39429. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  39430. }
  39431. // Vector2
  39432. for (name in this._vectors2) {
  39433. this._effect.setVector2(name, this._vectors2[name]);
  39434. }
  39435. // Vector3
  39436. for (name in this._vectors3) {
  39437. this._effect.setVector3(name, this._vectors3[name]);
  39438. }
  39439. // Vector4
  39440. for (name in this._vectors4) {
  39441. this._effect.setVector4(name, this._vectors4[name]);
  39442. }
  39443. // Matrix
  39444. for (name in this._matrices) {
  39445. this._effect.setMatrix(name, this._matrices[name]);
  39446. }
  39447. // Matrix 3x3
  39448. for (name in this._matrices3x3) {
  39449. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  39450. }
  39451. // Matrix 2x2
  39452. for (name in this._matrices2x2) {
  39453. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  39454. }
  39455. // Vector3Array
  39456. for (name in this._vectors3Arrays) {
  39457. this._effect.setArray3(name, this._vectors3Arrays[name]);
  39458. }
  39459. }
  39460. this._afterBind(mesh);
  39461. };
  39462. ShaderMaterial.prototype.getActiveTextures = function () {
  39463. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39464. for (var name in this._textures) {
  39465. activeTextures.push(this._textures[name]);
  39466. }
  39467. for (var name in this._textureArrays) {
  39468. var array = this._textureArrays[name];
  39469. for (var index = 0; index < array.length; index++) {
  39470. activeTextures.push(array[index]);
  39471. }
  39472. }
  39473. return activeTextures;
  39474. };
  39475. ShaderMaterial.prototype.hasTexture = function (texture) {
  39476. if (_super.prototype.hasTexture.call(this, texture)) {
  39477. return true;
  39478. }
  39479. for (var name in this._textures) {
  39480. if (this._textures[name] === texture) {
  39481. return true;
  39482. }
  39483. }
  39484. for (var name in this._textureArrays) {
  39485. var array = this._textureArrays[name];
  39486. for (var index = 0; index < array.length; index++) {
  39487. if (array[index] === texture) {
  39488. return true;
  39489. }
  39490. }
  39491. }
  39492. return false;
  39493. };
  39494. ShaderMaterial.prototype.clone = function (name) {
  39495. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  39496. return newShaderMaterial;
  39497. };
  39498. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39499. if (forceDisposeTextures) {
  39500. var name;
  39501. for (name in this._textures) {
  39502. this._textures[name].dispose();
  39503. }
  39504. for (name in this._textureArrays) {
  39505. var array = this._textureArrays[name];
  39506. for (var index = 0; index < array.length; index++) {
  39507. array[index].dispose();
  39508. }
  39509. }
  39510. }
  39511. this._textures = {};
  39512. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39513. };
  39514. ShaderMaterial.prototype.serialize = function () {
  39515. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39516. serializationObject.customType = "BABYLON.ShaderMaterial";
  39517. serializationObject.options = this._options;
  39518. serializationObject.shaderPath = this._shaderPath;
  39519. var name;
  39520. // Texture
  39521. serializationObject.textures = {};
  39522. for (name in this._textures) {
  39523. serializationObject.textures[name] = this._textures[name].serialize();
  39524. }
  39525. // Texture arrays
  39526. serializationObject.textureArrays = {};
  39527. for (name in this._textureArrays) {
  39528. serializationObject.textureArrays[name] = [];
  39529. var array = this._textureArrays[name];
  39530. for (var index = 0; index < array.length; index++) {
  39531. serializationObject.textureArrays[name].push(array[index].serialize());
  39532. }
  39533. }
  39534. // Float
  39535. serializationObject.floats = {};
  39536. for (name in this._floats) {
  39537. serializationObject.floats[name] = this._floats[name];
  39538. }
  39539. // Float s
  39540. serializationObject.floatArrays = {};
  39541. for (name in this._floatsArrays) {
  39542. serializationObject.floatArrays[name] = this._floatsArrays[name];
  39543. }
  39544. // Color3
  39545. serializationObject.colors3 = {};
  39546. for (name in this._colors3) {
  39547. serializationObject.colors3[name] = this._colors3[name].asArray();
  39548. }
  39549. // Color3 array
  39550. serializationObject.colors3Arrays = {};
  39551. for (name in this._colors3Arrays) {
  39552. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  39553. }
  39554. // Color4
  39555. serializationObject.colors4 = {};
  39556. for (name in this._colors4) {
  39557. serializationObject.colors4[name] = this._colors4[name].asArray();
  39558. }
  39559. // Vector2
  39560. serializationObject.vectors2 = {};
  39561. for (name in this._vectors2) {
  39562. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  39563. }
  39564. // Vector3
  39565. serializationObject.vectors3 = {};
  39566. for (name in this._vectors3) {
  39567. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  39568. }
  39569. // Vector4
  39570. serializationObject.vectors4 = {};
  39571. for (name in this._vectors4) {
  39572. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  39573. }
  39574. // Matrix
  39575. serializationObject.matrices = {};
  39576. for (name in this._matrices) {
  39577. serializationObject.matrices[name] = this._matrices[name].asArray();
  39578. }
  39579. // Matrix 3x3
  39580. serializationObject.matrices3x3 = {};
  39581. for (name in this._matrices3x3) {
  39582. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  39583. }
  39584. // Matrix 2x2
  39585. serializationObject.matrices2x2 = {};
  39586. for (name in this._matrices2x2) {
  39587. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  39588. }
  39589. // Vector3Array
  39590. serializationObject.vectors3Arrays = {};
  39591. for (name in this._vectors3Arrays) {
  39592. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  39593. }
  39594. return serializationObject;
  39595. };
  39596. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  39597. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  39598. var name;
  39599. // Texture
  39600. for (name in source.textures) {
  39601. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  39602. }
  39603. // Texture arrays
  39604. for (name in source.textureArrays) {
  39605. var array = source.textureArrays[name];
  39606. var textureArray = new Array();
  39607. for (var index = 0; index < array.length; index++) {
  39608. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  39609. }
  39610. material.setTextureArray(name, textureArray);
  39611. }
  39612. // Float
  39613. for (name in source.floats) {
  39614. material.setFloat(name, source.floats[name]);
  39615. }
  39616. // Float s
  39617. for (name in source.floatsArrays) {
  39618. material.setFloats(name, source.floatsArrays[name]);
  39619. }
  39620. // Color3
  39621. for (name in source.colors3) {
  39622. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  39623. }
  39624. // Color3 arrays
  39625. for (name in source.colors3Arrays) {
  39626. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  39627. if (i % 3 === 0) {
  39628. arr.push([num]);
  39629. }
  39630. else {
  39631. arr[arr.length - 1].push(num);
  39632. }
  39633. return arr;
  39634. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  39635. material.setColor3Array(name, colors);
  39636. }
  39637. // Color4
  39638. for (name in source.colors4) {
  39639. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  39640. }
  39641. // Vector2
  39642. for (name in source.vectors2) {
  39643. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  39644. }
  39645. // Vector3
  39646. for (name in source.vectors3) {
  39647. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  39648. }
  39649. // Vector4
  39650. for (name in source.vectors4) {
  39651. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  39652. }
  39653. // Matrix
  39654. for (name in source.matrices) {
  39655. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  39656. }
  39657. // Matrix 3x3
  39658. for (name in source.matrices3x3) {
  39659. material.setMatrix3x3(name, source.matrices3x3[name]);
  39660. }
  39661. // Matrix 2x2
  39662. for (name in source.matrices2x2) {
  39663. material.setMatrix2x2(name, source.matrices2x2[name]);
  39664. }
  39665. // Vector3Array
  39666. for (name in source.vectors3Arrays) {
  39667. material.setArray3(name, source.vectors3Arrays[name]);
  39668. }
  39669. return material;
  39670. };
  39671. return ShaderMaterial;
  39672. }(BABYLON.Material));
  39673. BABYLON.ShaderMaterial = ShaderMaterial;
  39674. })(BABYLON || (BABYLON = {}));
  39675. //# sourceMappingURL=babylon.shaderMaterial.js.map
  39676. var BABYLON;
  39677. (function (BABYLON) {
  39678. var MeshBuilder = (function () {
  39679. function MeshBuilder() {
  39680. }
  39681. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  39682. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  39683. return BABYLON.Mesh.DOUBLESIDE;
  39684. }
  39685. if (orientation === undefined || orientation === null) {
  39686. return BABYLON.Mesh.FRONTSIDE;
  39687. }
  39688. return orientation;
  39689. };
  39690. /**
  39691. * Creates a box mesh.
  39692. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  39693. * The parameter `size` sets the size (float) of each box side (default 1).
  39694. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  39695. * 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).
  39696. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  39697. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39698. * 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).
  39699. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39700. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39701. */
  39702. MeshBuilder.CreateBox = function (name, options, scene) {
  39703. var box = new BABYLON.Mesh(name, scene);
  39704. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39705. box.sideOrientation = options.sideOrientation;
  39706. var vertexData = BABYLON.VertexData.CreateBox(options);
  39707. vertexData.applyToMesh(box, options.updatable);
  39708. return box;
  39709. };
  39710. /**
  39711. * Creates a sphere mesh.
  39712. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  39713. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  39714. * 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`).
  39715. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  39716. * 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
  39717. * 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).
  39718. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39719. * 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).
  39720. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39721. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39722. */
  39723. MeshBuilder.CreateSphere = function (name, options, scene) {
  39724. var sphere = new BABYLON.Mesh(name, scene);
  39725. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39726. sphere.sideOrientation = options.sideOrientation;
  39727. var vertexData = BABYLON.VertexData.CreateSphere(options);
  39728. vertexData.applyToMesh(sphere, options.updatable);
  39729. return sphere;
  39730. };
  39731. /**
  39732. * Creates a plane polygonal mesh. By default, this is a disc.
  39733. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  39734. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  39735. * 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.
  39736. * 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
  39737. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39738. * 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).
  39739. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39740. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39741. */
  39742. MeshBuilder.CreateDisc = function (name, options, scene) {
  39743. var disc = new BABYLON.Mesh(name, scene);
  39744. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39745. disc.sideOrientation = options.sideOrientation;
  39746. var vertexData = BABYLON.VertexData.CreateDisc(options);
  39747. vertexData.applyToMesh(disc, options.updatable);
  39748. return disc;
  39749. };
  39750. /**
  39751. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  39752. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  39753. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  39754. * 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`).
  39755. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  39756. * 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.
  39757. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39758. * 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).
  39759. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39761. */
  39762. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  39763. var sphere = new BABYLON.Mesh(name, scene);
  39764. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39765. sphere.sideOrientation = options.sideOrientation;
  39766. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  39767. vertexData.applyToMesh(sphere, options.updatable);
  39768. return sphere;
  39769. };
  39770. ;
  39771. /**
  39772. * Creates a ribbon mesh.
  39773. * 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.
  39774. *
  39775. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  39776. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  39777. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  39778. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  39779. * 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.
  39780. * 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.
  39781. * 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
  39782. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39783. * 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).
  39784. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39785. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39786. * 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.
  39787. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  39788. * 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
  39789. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  39790. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  39791. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39792. */
  39793. MeshBuilder.CreateRibbon = function (name, options, scene) {
  39794. var pathArray = options.pathArray;
  39795. var closeArray = options.closeArray;
  39796. var closePath = options.closePath;
  39797. var offset = options.offset;
  39798. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39799. var instance = options.instance;
  39800. var updatable = options.updatable;
  39801. if (instance) {
  39802. // positionFunction : ribbon case
  39803. // only pathArray and sideOrientation parameters are taken into account for positions update
  39804. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  39805. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  39806. var positionFunction = function (positions) {
  39807. var minlg = pathArray[0].length;
  39808. var i = 0;
  39809. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  39810. for (var si = 1; si <= ns; si++) {
  39811. for (var p = 0; p < pathArray.length; p++) {
  39812. var path = pathArray[p];
  39813. var l = path.length;
  39814. minlg = (minlg < l) ? minlg : l;
  39815. var j = 0;
  39816. while (j < minlg) {
  39817. positions[i] = path[j].x;
  39818. positions[i + 1] = path[j].y;
  39819. positions[i + 2] = path[j].z;
  39820. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  39821. BABYLON.Tmp.Vector3[0].x = path[j].x;
  39822. }
  39823. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  39824. BABYLON.Tmp.Vector3[1].x = path[j].x;
  39825. }
  39826. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  39827. BABYLON.Tmp.Vector3[0].y = path[j].y;
  39828. }
  39829. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  39830. BABYLON.Tmp.Vector3[1].y = path[j].y;
  39831. }
  39832. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  39833. BABYLON.Tmp.Vector3[0].z = path[j].z;
  39834. }
  39835. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  39836. BABYLON.Tmp.Vector3[1].z = path[j].z;
  39837. }
  39838. j++;
  39839. i += 3;
  39840. }
  39841. if (instance._closePath) {
  39842. positions[i] = path[0].x;
  39843. positions[i + 1] = path[0].y;
  39844. positions[i + 2] = path[0].z;
  39845. i += 3;
  39846. }
  39847. }
  39848. }
  39849. };
  39850. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39851. positionFunction(positions);
  39852. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  39853. instance._boundingInfo.update(instance._worldMatrix);
  39854. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  39855. if (options.colors) {
  39856. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39857. for (var c = 0; c < options.colors.length; c++) {
  39858. colors[c * 4] = options.colors[c].r;
  39859. colors[c * 4 + 1] = options.colors[c].g;
  39860. colors[c * 4 + 2] = options.colors[c].b;
  39861. colors[c * 4 + 3] = options.colors[c].a;
  39862. }
  39863. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  39864. }
  39865. if (options.uvs) {
  39866. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39867. for (var i = 0; i < options.uvs.length; i++) {
  39868. uvs[i * 2] = options.uvs[i].x;
  39869. uvs[i * 2 + 1] = options.uvs[i].y;
  39870. }
  39871. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  39872. }
  39873. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  39874. var indices = instance.getIndices();
  39875. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39876. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  39877. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  39878. if (instance._closePath) {
  39879. var indexFirst = 0;
  39880. var indexLast = 0;
  39881. for (var p = 0; p < pathArray.length; p++) {
  39882. indexFirst = instance._idx[p] * 3;
  39883. if (p + 1 < pathArray.length) {
  39884. indexLast = (instance._idx[p + 1] - 1) * 3;
  39885. }
  39886. else {
  39887. indexLast = normals.length - 3;
  39888. }
  39889. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  39890. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  39891. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  39892. normals[indexLast] = normals[indexFirst];
  39893. normals[indexLast + 1] = normals[indexFirst + 1];
  39894. normals[indexLast + 2] = normals[indexFirst + 2];
  39895. }
  39896. }
  39897. if (!(instance.areNormalsFrozen)) {
  39898. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  39899. }
  39900. }
  39901. return instance;
  39902. }
  39903. else {
  39904. var ribbon = new BABYLON.Mesh(name, scene);
  39905. ribbon.sideOrientation = sideOrientation;
  39906. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  39907. if (closePath) {
  39908. ribbon._idx = vertexData._idx;
  39909. }
  39910. ribbon._closePath = closePath;
  39911. ribbon._closeArray = closeArray;
  39912. vertexData.applyToMesh(ribbon, updatable);
  39913. return ribbon;
  39914. }
  39915. };
  39916. /**
  39917. * Creates a cylinder or a cone mesh.
  39918. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  39919. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  39920. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  39921. * 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.
  39922. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  39923. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  39924. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  39925. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  39926. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  39927. * 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).
  39928. * 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
  39929. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  39930. * 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
  39931. * 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.
  39932. * If `enclose` is false, a ring surface is one element.
  39933. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  39934. * 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
  39935. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39936. * 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).
  39937. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39938. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39939. */
  39940. MeshBuilder.CreateCylinder = function (name, options, scene) {
  39941. var cylinder = new BABYLON.Mesh(name, scene);
  39942. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39943. cylinder.sideOrientation = options.sideOrientation;
  39944. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  39945. vertexData.applyToMesh(cylinder, options.updatable);
  39946. return cylinder;
  39947. };
  39948. /**
  39949. * Creates a torus mesh.
  39950. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  39951. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  39952. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  39953. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  39954. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39955. * 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).
  39956. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39957. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39958. */
  39959. MeshBuilder.CreateTorus = function (name, options, scene) {
  39960. var torus = new BABYLON.Mesh(name, scene);
  39961. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39962. torus.sideOrientation = options.sideOrientation;
  39963. var vertexData = BABYLON.VertexData.CreateTorus(options);
  39964. vertexData.applyToMesh(torus, options.updatable);
  39965. return torus;
  39966. };
  39967. /**
  39968. * Creates a torus knot mesh.
  39969. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  39970. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  39971. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  39972. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  39973. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  39974. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39975. * 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).
  39976. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39977. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39978. */
  39979. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  39980. var torusKnot = new BABYLON.Mesh(name, scene);
  39981. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39982. torusKnot.sideOrientation = options.sideOrientation;
  39983. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  39984. vertexData.applyToMesh(torusKnot, options.updatable);
  39985. return torusKnot;
  39986. };
  39987. /**
  39988. * Creates a line system mesh.
  39989. * A line system is a pool of many lines gathered in a single mesh.
  39990. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  39991. * 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.
  39992. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  39993. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  39994. * 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
  39995. * 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
  39996. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  39997. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39998. */
  39999. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  40000. var instance = options.instance;
  40001. var lines = options.lines;
  40002. if (instance) {
  40003. var positionFunction = function (positions) {
  40004. var i = 0;
  40005. for (var l = 0; l < lines.length; l++) {
  40006. var points = lines[l];
  40007. for (var p = 0; p < points.length; p++) {
  40008. positions[i] = points[p].x;
  40009. positions[i + 1] = points[p].y;
  40010. positions[i + 2] = points[p].z;
  40011. i += 3;
  40012. }
  40013. }
  40014. };
  40015. instance.updateMeshPositions(positionFunction, false);
  40016. return instance;
  40017. }
  40018. // line system creation
  40019. var lineSystem = new BABYLON.LinesMesh(name, scene);
  40020. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  40021. vertexData.applyToMesh(lineSystem, options.updatable);
  40022. return lineSystem;
  40023. };
  40024. /**
  40025. * Creates a line mesh.
  40026. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  40027. * 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.
  40028. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  40029. * The parameter `points` is an array successive Vector3.
  40030. * 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
  40031. * When updating an instance, remember that only point positions can change, not the number of points.
  40032. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40033. */
  40034. MeshBuilder.CreateLines = function (name, options, scene) {
  40035. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  40036. return lines;
  40037. };
  40038. /**
  40039. * Creates a dashed line mesh.
  40040. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  40041. * 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.
  40042. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  40043. * The parameter `points` is an array successive Vector3.
  40044. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  40045. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  40046. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  40047. * 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
  40048. * When updating an instance, remember that only point positions can change, not the number of points.
  40049. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40050. */
  40051. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  40052. var points = options.points;
  40053. var instance = options.instance;
  40054. var gapSize = options.gapSize;
  40055. var dashNb = options.dashNb;
  40056. var dashSize = options.dashSize;
  40057. if (instance) {
  40058. var positionFunction = function (positions) {
  40059. var curvect = BABYLON.Vector3.Zero();
  40060. var nbSeg = positions.length / 6;
  40061. var lg = 0;
  40062. var nb = 0;
  40063. var shft = 0;
  40064. var dashshft = 0;
  40065. var curshft = 0;
  40066. var p = 0;
  40067. var i = 0;
  40068. var j = 0;
  40069. for (i = 0; i < points.length - 1; i++) {
  40070. points[i + 1].subtractToRef(points[i], curvect);
  40071. lg += curvect.length();
  40072. }
  40073. shft = lg / nbSeg;
  40074. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  40075. for (i = 0; i < points.length - 1; i++) {
  40076. points[i + 1].subtractToRef(points[i], curvect);
  40077. nb = Math.floor(curvect.length() / shft);
  40078. curvect.normalize();
  40079. j = 0;
  40080. while (j < nb && p < positions.length) {
  40081. curshft = shft * j;
  40082. positions[p] = points[i].x + curshft * curvect.x;
  40083. positions[p + 1] = points[i].y + curshft * curvect.y;
  40084. positions[p + 2] = points[i].z + curshft * curvect.z;
  40085. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  40086. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  40087. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  40088. p += 6;
  40089. j++;
  40090. }
  40091. }
  40092. while (p < positions.length) {
  40093. positions[p] = points[i].x;
  40094. positions[p + 1] = points[i].y;
  40095. positions[p + 2] = points[i].z;
  40096. p += 3;
  40097. }
  40098. };
  40099. instance.updateMeshPositions(positionFunction, false);
  40100. return instance;
  40101. }
  40102. // dashed lines creation
  40103. var dashedLines = new BABYLON.LinesMesh(name, scene);
  40104. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  40105. vertexData.applyToMesh(dashedLines, options.updatable);
  40106. dashedLines.dashSize = dashSize;
  40107. dashedLines.gapSize = gapSize;
  40108. return dashedLines;
  40109. };
  40110. /**
  40111. * Creates an extruded shape mesh.
  40112. * 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.
  40113. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  40114. *
  40115. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40116. * 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
  40117. * extruded along the Z axis.
  40118. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40119. * 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.
  40120. * The parameter `scale` (float, default 1) is the value to scale the shape.
  40121. * 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
  40122. * 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
  40123. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40124. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40125. * 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).
  40126. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40127. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40128. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40129. */
  40130. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  40131. var path = options.path;
  40132. var shape = options.shape;
  40133. var scale = options.scale || 1;
  40134. var rotation = options.rotation || 0;
  40135. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40136. var updatable = options.updatable;
  40137. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40138. var instance = options.instance;
  40139. var invertUV = options.invertUV || false;
  40140. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40141. };
  40142. /**
  40143. * Creates an custom extruded shape mesh.
  40144. * 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.
  40145. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  40146. *
  40147. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40148. * 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
  40149. * extruded along the Z axis.
  40150. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40151. * 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
  40152. * and the distance of this point from the begining of the path :
  40153. * ```javascript
  40154. * var rotationFunction = function(i, distance) {
  40155. * // do things
  40156. * return rotationValue; }
  40157. * ```
  40158. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  40159. * 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
  40160. * and the distance of this point from the begining of the path :
  40161. * ```javascript
  40162. * var scaleFunction = function(i, distance) {
  40163. * // do things
  40164. * return scaleValue;}
  40165. * ```
  40166. * It must returns a float value that will be the scale value applied to the shape on each path point.
  40167. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  40168. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  40169. * 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
  40170. * 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
  40171. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40172. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40173. * 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).
  40174. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40175. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40176. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40177. */
  40178. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  40179. var path = options.path;
  40180. var shape = options.shape;
  40181. var scaleFunction = options.scaleFunction || (function () { return 1; });
  40182. var rotationFunction = options.rotationFunction || (function () { return 0; });
  40183. var ribbonCloseArray = options.ribbonCloseArray || false;
  40184. var ribbonClosePath = options.ribbonClosePath || false;
  40185. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40186. var updatable = options.updatable;
  40187. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40188. var instance = options.instance;
  40189. var invertUV = options.invertUV || false;
  40190. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40191. };
  40192. /**
  40193. * Creates lathe mesh.
  40194. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  40195. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  40196. *
  40197. * 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
  40198. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  40199. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  40200. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  40201. * 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.
  40202. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  40203. * 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
  40204. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40205. * 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).
  40206. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40207. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40208. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40209. */
  40210. MeshBuilder.CreateLathe = function (name, options, scene) {
  40211. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  40212. var closed = (options.closed === undefined) ? true : options.closed;
  40213. var shape = options.shape;
  40214. var radius = options.radius || 1;
  40215. var tessellation = options.tessellation || 64;
  40216. var updatable = options.updatable;
  40217. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40218. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40219. var pi2 = Math.PI * 2;
  40220. var paths = new Array();
  40221. var invertUV = options.invertUV || false;
  40222. var i = 0;
  40223. var p = 0;
  40224. var step = pi2 / tessellation * arc;
  40225. var rotated;
  40226. var path = new Array();
  40227. ;
  40228. for (i = 0; i <= tessellation; i++) {
  40229. var path = [];
  40230. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  40231. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  40232. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  40233. }
  40234. for (p = 0; p < shape.length; p++) {
  40235. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  40236. path.push(rotated);
  40237. }
  40238. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  40239. 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));
  40240. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  40241. }
  40242. paths.push(path);
  40243. }
  40244. // lathe ribbon
  40245. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40246. return lathe;
  40247. };
  40248. /**
  40249. * Creates a plane mesh.
  40250. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40251. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  40252. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  40253. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  40254. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40255. * 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).
  40256. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40257. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40258. */
  40259. MeshBuilder.CreatePlane = function (name, options, scene) {
  40260. var plane = new BABYLON.Mesh(name, scene);
  40261. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40262. plane.sideOrientation = options.sideOrientation;
  40263. var vertexData = BABYLON.VertexData.CreatePlane(options);
  40264. vertexData.applyToMesh(plane, options.updatable);
  40265. if (options.sourcePlane) {
  40266. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  40267. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  40268. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  40269. plane.rotate(vectorProduct, product);
  40270. }
  40271. return plane;
  40272. };
  40273. /**
  40274. * Creates a ground mesh.
  40275. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40276. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  40277. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  40278. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40279. */
  40280. MeshBuilder.CreateGround = function (name, options, scene) {
  40281. var ground = new BABYLON.GroundMesh(name, scene);
  40282. ground._setReady(false);
  40283. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  40284. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  40285. ground._width = options.width || 1;
  40286. ground._height = options.height || 1;
  40287. ground._maxX = ground._width / 2;
  40288. ground._maxZ = ground._height / 2;
  40289. ground._minX = -ground._maxX;
  40290. ground._minZ = -ground._maxZ;
  40291. var vertexData = BABYLON.VertexData.CreateGround(options);
  40292. vertexData.applyToMesh(ground, options.updatable);
  40293. ground._setReady(true);
  40294. return ground;
  40295. };
  40296. /**
  40297. * Creates a tiled ground mesh.
  40298. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  40299. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  40300. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  40301. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  40302. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  40303. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  40304. * numbers of subdivisions on the ground width and height of each tile.
  40305. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40306. */
  40307. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  40308. var tiledGround = new BABYLON.Mesh(name, scene);
  40309. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  40310. vertexData.applyToMesh(tiledGround, options.updatable);
  40311. return tiledGround;
  40312. };
  40313. /**
  40314. * Creates a ground mesh from a height map.
  40315. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  40316. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  40317. * The parameter `url` sets the URL of the height map image resource.
  40318. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  40319. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  40320. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  40321. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  40322. * 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.
  40323. * 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).
  40324. * This function is passed the newly built mesh :
  40325. * ```javascript
  40326. * function(mesh) { // do things
  40327. * return; }
  40328. * ```
  40329. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40330. */
  40331. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  40332. var width = options.width || 10.0;
  40333. var height = options.height || 10.0;
  40334. var subdivisions = options.subdivisions || 1 | 0;
  40335. var minHeight = options.minHeight || 0.0;
  40336. var maxHeight = options.maxHeight || 10.0;
  40337. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  40338. var updatable = options.updatable;
  40339. var onReady = options.onReady;
  40340. var ground = new BABYLON.GroundMesh(name, scene);
  40341. ground._subdivisionsX = subdivisions;
  40342. ground._subdivisionsY = subdivisions;
  40343. ground._width = width;
  40344. ground._height = height;
  40345. ground._maxX = ground._width / 2.0;
  40346. ground._maxZ = ground._height / 2.0;
  40347. ground._minX = -ground._maxX;
  40348. ground._minZ = -ground._maxZ;
  40349. ground._setReady(false);
  40350. var onload = function (img) {
  40351. // Getting height map data
  40352. var canvas = document.createElement("canvas");
  40353. var context = canvas.getContext("2d");
  40354. var bufferWidth = img.width;
  40355. var bufferHeight = img.height;
  40356. canvas.width = bufferWidth;
  40357. canvas.height = bufferHeight;
  40358. context.drawImage(img, 0, 0);
  40359. // Create VertexData from map data
  40360. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  40361. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  40362. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  40363. width: width, height: height,
  40364. subdivisions: subdivisions,
  40365. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  40366. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  40367. });
  40368. vertexData.applyToMesh(ground, updatable);
  40369. ground._setReady(true);
  40370. //execute ready callback, if set
  40371. if (onReady) {
  40372. onReady(ground);
  40373. }
  40374. };
  40375. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  40376. return ground;
  40377. };
  40378. /**
  40379. * Creates a polygon mesh.
  40380. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  40381. * 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.
  40382. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40383. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40384. * 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).
  40385. * Remember you can only change the shape positions, not their number when updating a polygon.
  40386. */
  40387. MeshBuilder.CreatePolygon = function (name, options, scene) {
  40388. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40389. var shape = options.shape;
  40390. var holes = options.holes || [];
  40391. var depth = options.depth || 0;
  40392. var contours = [];
  40393. var hole = [];
  40394. for (var i = 0; i < shape.length; i++) {
  40395. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  40396. }
  40397. var epsilon = 0.00000001;
  40398. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  40399. contours.pop();
  40400. }
  40401. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  40402. for (var hNb = 0; hNb < holes.length; hNb++) {
  40403. hole = [];
  40404. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  40405. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  40406. }
  40407. polygonTriangulation.addHole(hole);
  40408. }
  40409. var polygon = polygonTriangulation.build(options.updatable, depth);
  40410. polygon.sideOrientation = options.sideOrientation;
  40411. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  40412. vertexData.applyToMesh(polygon, options.updatable);
  40413. return polygon;
  40414. };
  40415. ;
  40416. /**
  40417. * Creates an extruded polygon mesh, with depth in the Y direction.
  40418. * 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).
  40419. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  40420. */
  40421. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  40422. return MeshBuilder.CreatePolygon(name, options, scene);
  40423. };
  40424. ;
  40425. /**
  40426. * Creates a tube mesh.
  40427. * 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.
  40428. *
  40429. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  40430. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  40431. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  40432. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  40433. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  40434. * 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.
  40435. * It must return a radius value (positive float) :
  40436. * ```javascript
  40437. * var radiusFunction = function(i, distance) {
  40438. * // do things
  40439. * return radius; }
  40440. * ```
  40441. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  40442. * 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
  40443. * 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
  40444. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40445. * 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).
  40446. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40447. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40448. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40449. */
  40450. MeshBuilder.CreateTube = function (name, options, scene) {
  40451. var path = options.path;
  40452. var radius = options.radius || 1.0;
  40453. var tessellation = options.tessellation || 64 | 0;
  40454. var radiusFunction = options.radiusFunction;
  40455. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40456. var invertUV = options.invertUV || false;
  40457. var updatable = options.updatable;
  40458. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40459. var instance = options.instance;
  40460. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  40461. // tube geometry
  40462. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  40463. var tangents = path3D.getTangents();
  40464. var normals = path3D.getNormals();
  40465. var distances = path3D.getDistances();
  40466. var pi2 = Math.PI * 2;
  40467. var step = pi2 / tessellation * arc;
  40468. var returnRadius = function () { return radius; };
  40469. var radiusFunctionFinal = radiusFunction || returnRadius;
  40470. var circlePath;
  40471. var rad;
  40472. var normal;
  40473. var rotated;
  40474. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  40475. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  40476. for (var i = 0; i < path.length; i++) {
  40477. rad = radiusFunctionFinal(i, distances[i]); // current radius
  40478. circlePath = Array(); // current circle array
  40479. normal = normals[i]; // current normal
  40480. for (var t = 0; t < tessellation; t++) {
  40481. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  40482. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  40483. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  40484. rotated.scaleInPlace(rad).addInPlace(path[i]);
  40485. circlePath[t] = rotated;
  40486. }
  40487. circlePaths[index] = circlePath;
  40488. index++;
  40489. }
  40490. // cap
  40491. var capPath = function (nbPoints, pathIndex) {
  40492. var pointCap = Array();
  40493. for (var i = 0; i < nbPoints; i++) {
  40494. pointCap.push(path[pathIndex]);
  40495. }
  40496. return pointCap;
  40497. };
  40498. switch (cap) {
  40499. case BABYLON.Mesh.NO_CAP:
  40500. break;
  40501. case BABYLON.Mesh.CAP_START:
  40502. circlePaths[0] = capPath(tessellation, 0);
  40503. circlePaths[1] = circlePaths[2].slice(0);
  40504. break;
  40505. case BABYLON.Mesh.CAP_END:
  40506. circlePaths[index] = circlePaths[index - 1].slice(0);
  40507. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  40508. break;
  40509. case BABYLON.Mesh.CAP_ALL:
  40510. circlePaths[0] = capPath(tessellation, 0);
  40511. circlePaths[1] = circlePaths[2].slice(0);
  40512. circlePaths[index] = circlePaths[index - 1].slice(0);
  40513. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  40514. break;
  40515. default:
  40516. break;
  40517. }
  40518. return circlePaths;
  40519. };
  40520. var path3D;
  40521. var pathArray;
  40522. if (instance) {
  40523. var arc = options.arc || instance.arc;
  40524. path3D = (instance.path3D).update(path);
  40525. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  40526. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  40527. instance.path3D = path3D;
  40528. instance.pathArray = pathArray;
  40529. instance.arc = arc;
  40530. return instance;
  40531. }
  40532. // tube creation
  40533. path3D = new BABYLON.Path3D(path);
  40534. var newPathArray = new Array();
  40535. cap = (cap < 0 || cap > 3) ? 0 : cap;
  40536. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  40537. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40538. tube.pathArray = pathArray;
  40539. tube.path3D = path3D;
  40540. tube.tessellation = tessellation;
  40541. tube.cap = cap;
  40542. tube.arc = options.arc;
  40543. return tube;
  40544. };
  40545. /**
  40546. * Creates a polyhedron mesh.
  40547. *
  40548. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  40549. * 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
  40550. * to choose the wanted type.
  40551. * The parameter `size` (positive float, default 1) sets the polygon size.
  40552. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  40553. * 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`.
  40554. * 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
  40555. * 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)`).
  40556. * 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
  40557. * 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.
  40558. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40559. * 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).
  40560. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40562. */
  40563. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  40564. var polyhedron = new BABYLON.Mesh(name, scene);
  40565. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40566. polyhedron.sideOrientation = options.sideOrientation;
  40567. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  40568. vertexData.applyToMesh(polyhedron, options.updatable);
  40569. return polyhedron;
  40570. };
  40571. /**
  40572. * Creates a decal mesh.
  40573. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  40574. * 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.
  40575. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  40576. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  40577. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  40578. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  40579. */
  40580. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  40581. var indices = sourceMesh.getIndices();
  40582. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40583. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40584. var position = options.position || BABYLON.Vector3.Zero();
  40585. var normal = options.normal || BABYLON.Vector3.Up();
  40586. var size = options.size || BABYLON.Vector3.One();
  40587. var angle = options.angle || 0;
  40588. // Getting correct rotation
  40589. if (!normal) {
  40590. var target = new BABYLON.Vector3(0, 0, 1);
  40591. var camera = sourceMesh.getScene().activeCamera;
  40592. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  40593. normal = camera.globalPosition.subtract(cameraWorldTarget);
  40594. }
  40595. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  40596. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  40597. var pitch = Math.atan2(normal.y, len);
  40598. // Matrix
  40599. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  40600. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  40601. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  40602. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  40603. var vertexData = new BABYLON.VertexData();
  40604. vertexData.indices = [];
  40605. vertexData.positions = [];
  40606. vertexData.normals = [];
  40607. vertexData.uvs = [];
  40608. var currentVertexDataIndex = 0;
  40609. var extractDecalVector3 = function (indexId) {
  40610. var vertexId = indices[indexId];
  40611. var result = new BABYLON.PositionNormalVertex();
  40612. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  40613. // Send vector to decal local world
  40614. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  40615. // Get normal
  40616. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  40617. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  40618. return result;
  40619. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  40620. var clip = function (vertices, axis) {
  40621. if (vertices.length === 0) {
  40622. return vertices;
  40623. }
  40624. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  40625. var clipVertices = function (v0, v1) {
  40626. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  40627. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  40628. };
  40629. var result = new Array();
  40630. for (var index = 0; index < vertices.length; index += 3) {
  40631. var v1Out;
  40632. var v2Out;
  40633. var v3Out;
  40634. var total = 0;
  40635. var nV1, nV2, nV3, nV4;
  40636. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  40637. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  40638. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  40639. v1Out = d1 > 0;
  40640. v2Out = d2 > 0;
  40641. v3Out = d3 > 0;
  40642. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  40643. switch (total) {
  40644. case 0:
  40645. result.push(vertices[index]);
  40646. result.push(vertices[index + 1]);
  40647. result.push(vertices[index + 2]);
  40648. break;
  40649. case 1:
  40650. if (v1Out) {
  40651. nV1 = vertices[index + 1];
  40652. nV2 = vertices[index + 2];
  40653. nV3 = clipVertices(vertices[index], nV1);
  40654. nV4 = clipVertices(vertices[index], nV2);
  40655. }
  40656. if (v2Out) {
  40657. nV1 = vertices[index];
  40658. nV2 = vertices[index + 2];
  40659. nV3 = clipVertices(vertices[index + 1], nV1);
  40660. nV4 = clipVertices(vertices[index + 1], nV2);
  40661. result.push(nV3);
  40662. result.push(nV2.clone());
  40663. result.push(nV1.clone());
  40664. result.push(nV2.clone());
  40665. result.push(nV3.clone());
  40666. result.push(nV4);
  40667. break;
  40668. }
  40669. if (v3Out) {
  40670. nV1 = vertices[index];
  40671. nV2 = vertices[index + 1];
  40672. nV3 = clipVertices(vertices[index + 2], nV1);
  40673. nV4 = clipVertices(vertices[index + 2], nV2);
  40674. }
  40675. result.push(nV1.clone());
  40676. result.push(nV2.clone());
  40677. result.push(nV3);
  40678. result.push(nV4);
  40679. result.push(nV3.clone());
  40680. result.push(nV2.clone());
  40681. break;
  40682. case 2:
  40683. if (!v1Out) {
  40684. nV1 = vertices[index].clone();
  40685. nV2 = clipVertices(nV1, vertices[index + 1]);
  40686. nV3 = clipVertices(nV1, vertices[index + 2]);
  40687. result.push(nV1);
  40688. result.push(nV2);
  40689. result.push(nV3);
  40690. }
  40691. if (!v2Out) {
  40692. nV1 = vertices[index + 1].clone();
  40693. nV2 = clipVertices(nV1, vertices[index + 2]);
  40694. nV3 = clipVertices(nV1, vertices[index]);
  40695. result.push(nV1);
  40696. result.push(nV2);
  40697. result.push(nV3);
  40698. }
  40699. if (!v3Out) {
  40700. nV1 = vertices[index + 2].clone();
  40701. nV2 = clipVertices(nV1, vertices[index]);
  40702. nV3 = clipVertices(nV1, vertices[index + 1]);
  40703. result.push(nV1);
  40704. result.push(nV2);
  40705. result.push(nV3);
  40706. }
  40707. break;
  40708. case 3:
  40709. break;
  40710. }
  40711. }
  40712. return result;
  40713. };
  40714. for (var index = 0; index < indices.length; index += 3) {
  40715. var faceVertices = new Array();
  40716. faceVertices.push(extractDecalVector3(index));
  40717. faceVertices.push(extractDecalVector3(index + 1));
  40718. faceVertices.push(extractDecalVector3(index + 2));
  40719. // Clip
  40720. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  40721. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  40722. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  40723. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  40724. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  40725. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  40726. if (faceVertices.length === 0) {
  40727. continue;
  40728. }
  40729. // Add UVs and get back to world
  40730. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  40731. var vertex = faceVertices[vIndex];
  40732. //TODO check for Int32Array | Uint32Array | Uint16Array
  40733. vertexData.indices.push(currentVertexDataIndex);
  40734. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  40735. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  40736. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  40737. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  40738. currentVertexDataIndex++;
  40739. }
  40740. }
  40741. // Return mesh
  40742. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  40743. vertexData.applyToMesh(decal);
  40744. decal.position = position.clone();
  40745. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  40746. return decal;
  40747. };
  40748. // Privates
  40749. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  40750. // extrusion geometry
  40751. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  40752. var tangents = path3D.getTangents();
  40753. var normals = path3D.getNormals();
  40754. var binormals = path3D.getBinormals();
  40755. var distances = path3D.getDistances();
  40756. var angle = 0;
  40757. var returnScale = function () { return scale; };
  40758. var returnRotation = function () { return rotation; };
  40759. var rotate = custom ? rotateFunction : returnRotation;
  40760. var scl = custom ? scaleFunction : returnScale;
  40761. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  40762. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  40763. for (var i = 0; i < curve.length; i++) {
  40764. var shapePath = new Array();
  40765. var angleStep = rotate(i, distances[i]);
  40766. var scaleRatio = scl(i, distances[i]);
  40767. for (var p = 0; p < shape.length; p++) {
  40768. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  40769. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  40770. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  40771. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  40772. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  40773. shapePath[p] = rotated;
  40774. }
  40775. shapePaths[index] = shapePath;
  40776. angle += angleStep;
  40777. index++;
  40778. }
  40779. // cap
  40780. var capPath = function (shapePath) {
  40781. var pointCap = Array();
  40782. var barycenter = BABYLON.Vector3.Zero();
  40783. var i;
  40784. for (i = 0; i < shapePath.length; i++) {
  40785. barycenter.addInPlace(shapePath[i]);
  40786. }
  40787. barycenter.scaleInPlace(1.0 / shapePath.length);
  40788. for (i = 0; i < shapePath.length; i++) {
  40789. pointCap.push(barycenter);
  40790. }
  40791. return pointCap;
  40792. };
  40793. switch (cap) {
  40794. case BABYLON.Mesh.NO_CAP:
  40795. break;
  40796. case BABYLON.Mesh.CAP_START:
  40797. shapePaths[0] = capPath(shapePaths[2]);
  40798. shapePaths[1] = shapePaths[2];
  40799. break;
  40800. case BABYLON.Mesh.CAP_END:
  40801. shapePaths[index] = shapePaths[index - 1];
  40802. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  40803. break;
  40804. case BABYLON.Mesh.CAP_ALL:
  40805. shapePaths[0] = capPath(shapePaths[2]);
  40806. shapePaths[1] = shapePaths[2];
  40807. shapePaths[index] = shapePaths[index - 1];
  40808. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  40809. break;
  40810. default:
  40811. break;
  40812. }
  40813. return shapePaths;
  40814. };
  40815. var path3D;
  40816. var pathArray;
  40817. if (instance) {
  40818. path3D = (instance.path3D).update(curve);
  40819. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  40820. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  40821. return instance;
  40822. }
  40823. // extruded shape creation
  40824. path3D = new BABYLON.Path3D(curve);
  40825. var newShapePaths = new Array();
  40826. cap = (cap < 0 || cap > 3) ? 0 : cap;
  40827. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  40828. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  40829. extrudedGeneric.pathArray = pathArray;
  40830. extrudedGeneric.path3D = path3D;
  40831. extrudedGeneric.cap = cap;
  40832. return extrudedGeneric;
  40833. };
  40834. return MeshBuilder;
  40835. }());
  40836. BABYLON.MeshBuilder = MeshBuilder;
  40837. })(BABYLON || (BABYLON = {}));
  40838. //# sourceMappingURL=babylon.meshBuilder.js.map
  40839. var BABYLON;
  40840. (function (BABYLON) {
  40841. var Layer = (function () {
  40842. function Layer(name, imgUrl, scene, isBackground, color) {
  40843. this.name = name;
  40844. this.scale = new BABYLON.Vector2(1, 1);
  40845. this.offset = new BABYLON.Vector2(0, 0);
  40846. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  40847. this.layerMask = 0x0FFFFFFF;
  40848. this._vertexBuffers = {};
  40849. // Events
  40850. /**
  40851. * An event triggered when the layer is disposed.
  40852. * @type {BABYLON.Observable}
  40853. */
  40854. this.onDisposeObservable = new BABYLON.Observable();
  40855. /**
  40856. * An event triggered before rendering the scene
  40857. * @type {BABYLON.Observable}
  40858. */
  40859. this.onBeforeRenderObservable = new BABYLON.Observable();
  40860. /**
  40861. * An event triggered after rendering the scene
  40862. * @type {BABYLON.Observable}
  40863. */
  40864. this.onAfterRenderObservable = new BABYLON.Observable();
  40865. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  40866. this.isBackground = isBackground === undefined ? true : isBackground;
  40867. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  40868. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40869. this._scene.layers.push(this);
  40870. var engine = this._scene.getEngine();
  40871. // VBO
  40872. var vertices = [];
  40873. vertices.push(1, 1);
  40874. vertices.push(-1, 1);
  40875. vertices.push(-1, -1);
  40876. vertices.push(1, -1);
  40877. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40878. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  40879. this._createIndexBuffer();
  40880. // Effects
  40881. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  40882. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  40883. }
  40884. Object.defineProperty(Layer.prototype, "onDispose", {
  40885. set: function (callback) {
  40886. if (this._onDisposeObserver) {
  40887. this.onDisposeObservable.remove(this._onDisposeObserver);
  40888. }
  40889. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  40890. },
  40891. enumerable: true,
  40892. configurable: true
  40893. });
  40894. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  40895. set: function (callback) {
  40896. if (this._onBeforeRenderObserver) {
  40897. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40898. }
  40899. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40900. },
  40901. enumerable: true,
  40902. configurable: true
  40903. });
  40904. Object.defineProperty(Layer.prototype, "onAfterRender", {
  40905. set: function (callback) {
  40906. if (this._onAfterRenderObserver) {
  40907. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40908. }
  40909. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40910. },
  40911. enumerable: true,
  40912. configurable: true
  40913. });
  40914. Layer.prototype._createIndexBuffer = function () {
  40915. var engine = this._scene.getEngine();
  40916. // Indices
  40917. var indices = [];
  40918. indices.push(0);
  40919. indices.push(1);
  40920. indices.push(2);
  40921. indices.push(0);
  40922. indices.push(2);
  40923. indices.push(3);
  40924. this._indexBuffer = engine.createIndexBuffer(indices);
  40925. };
  40926. Layer.prototype._rebuild = function () {
  40927. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  40928. this._createIndexBuffer();
  40929. };
  40930. Layer.prototype.render = function () {
  40931. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  40932. // Check
  40933. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  40934. return;
  40935. var engine = this._scene.getEngine();
  40936. this.onBeforeRenderObservable.notifyObservers(this);
  40937. // Render
  40938. engine.enableEffect(currentEffect);
  40939. engine.setState(false);
  40940. // Texture
  40941. currentEffect.setTexture("textureSampler", this.texture);
  40942. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  40943. // Color
  40944. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  40945. // Scale / offset
  40946. currentEffect.setVector2("offset", this.offset);
  40947. currentEffect.setVector2("scale", this.scale);
  40948. // VBOs
  40949. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  40950. // Draw order
  40951. if (!this.alphaTest) {
  40952. engine.setAlphaMode(this.alphaBlendingMode);
  40953. engine.draw(true, 0, 6);
  40954. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40955. }
  40956. else {
  40957. engine.draw(true, 0, 6);
  40958. }
  40959. this.onAfterRenderObservable.notifyObservers(this);
  40960. };
  40961. Layer.prototype.dispose = function () {
  40962. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40963. if (vertexBuffer) {
  40964. vertexBuffer.dispose();
  40965. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40966. }
  40967. if (this._indexBuffer) {
  40968. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40969. this._indexBuffer = null;
  40970. }
  40971. if (this.texture) {
  40972. this.texture.dispose();
  40973. this.texture = null;
  40974. }
  40975. // Remove from scene
  40976. var index = this._scene.layers.indexOf(this);
  40977. this._scene.layers.splice(index, 1);
  40978. // Callback
  40979. this.onDisposeObservable.notifyObservers(this);
  40980. this.onDisposeObservable.clear();
  40981. this.onAfterRenderObservable.clear();
  40982. this.onBeforeRenderObservable.clear();
  40983. };
  40984. return Layer;
  40985. }());
  40986. BABYLON.Layer = Layer;
  40987. })(BABYLON || (BABYLON = {}));
  40988. //# sourceMappingURL=babylon.layer.js.map
  40989. var BABYLON;
  40990. (function (BABYLON) {
  40991. var BlurPostProcess = (function (_super) {
  40992. __extends(BlurPostProcess, _super);
  40993. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  40994. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40995. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40996. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  40997. _this.direction = direction;
  40998. _this._packedFloat = false;
  40999. _this.onApplyObservable.add(function (effect) {
  41000. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  41001. });
  41002. _this.kernel = kernel;
  41003. return _this;
  41004. }
  41005. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  41006. /**
  41007. * Gets the length in pixels of the blur sample region
  41008. */
  41009. get: function () {
  41010. return this._idealKernel;
  41011. },
  41012. /**
  41013. * Sets the length in pixels of the blur sample region
  41014. */
  41015. set: function (v) {
  41016. if (this._idealKernel === v) {
  41017. return;
  41018. }
  41019. v = Math.max(v, 1);
  41020. this._idealKernel = v;
  41021. this._kernel = this._nearestBestKernel(v);
  41022. this._updateParameters();
  41023. },
  41024. enumerable: true,
  41025. configurable: true
  41026. });
  41027. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  41028. /**
  41029. * Gets wether or not the blur is unpacking/repacking floats
  41030. */
  41031. get: function () {
  41032. return this._packedFloat;
  41033. },
  41034. /**
  41035. * Sets wether or not the blur needs to unpack/repack floats
  41036. */
  41037. set: function (v) {
  41038. if (this._packedFloat === v) {
  41039. return;
  41040. }
  41041. this._packedFloat = v;
  41042. this._updateParameters();
  41043. },
  41044. enumerable: true,
  41045. configurable: true
  41046. });
  41047. BlurPostProcess.prototype._updateParameters = function () {
  41048. // Generate sampling offsets and weights
  41049. var N = this._kernel;
  41050. var centerIndex = (N - 1) / 2;
  41051. // Generate Gaussian sampling weights over kernel
  41052. var offsets = [];
  41053. var weights = [];
  41054. var totalWeight = 0;
  41055. for (var i = 0; i < N; i++) {
  41056. var u = i / (N - 1);
  41057. var w = this._gaussianWeight(u * 2.0 - 1);
  41058. offsets[i] = (i - centerIndex);
  41059. weights[i] = w;
  41060. totalWeight += w;
  41061. }
  41062. // Normalize weights
  41063. for (var i = 0; i < weights.length; i++) {
  41064. weights[i] /= totalWeight;
  41065. }
  41066. // Optimize: combine samples to take advantage of hardware linear sampling
  41067. // Walk from left to center, combining pairs (symmetrically)
  41068. var linearSamplingWeights = [];
  41069. var linearSamplingOffsets = [];
  41070. var linearSamplingMap = [];
  41071. for (var i = 0; i <= centerIndex; i += 2) {
  41072. var j = Math.min(i + 1, Math.floor(centerIndex));
  41073. var singleCenterSample = i === j;
  41074. if (singleCenterSample) {
  41075. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  41076. }
  41077. else {
  41078. var sharedCell = j === centerIndex;
  41079. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  41080. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  41081. if (offsetLinear === 0) {
  41082. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  41083. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  41084. }
  41085. else {
  41086. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  41087. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  41088. }
  41089. }
  41090. }
  41091. for (var i = 0; i < linearSamplingMap.length; i++) {
  41092. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  41093. linearSamplingWeights[i] = linearSamplingMap[i].w;
  41094. }
  41095. // Replace with optimized
  41096. offsets = linearSamplingOffsets;
  41097. weights = linearSamplingWeights;
  41098. // Generate shaders
  41099. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  41100. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  41101. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  41102. var defines = "";
  41103. for (var i = 0; i < varyingCount; i++) {
  41104. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  41105. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  41106. }
  41107. var depCount = 0;
  41108. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  41109. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  41110. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  41111. depCount++;
  41112. }
  41113. if (this.packedFloat) {
  41114. defines += "#define PACKEDFLOAT 1";
  41115. }
  41116. this.updateEffect(defines, null, null, {
  41117. varyingCount: varyingCount,
  41118. depCount: depCount
  41119. });
  41120. };
  41121. /**
  41122. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  41123. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  41124. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  41125. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  41126. * The gaps between physical kernels are compensated for in the weighting of the samples
  41127. * @param idealKernel Ideal blur kernel.
  41128. * @return Nearest best kernel.
  41129. */
  41130. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  41131. var v = Math.round(idealKernel);
  41132. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  41133. var k = _a[_i];
  41134. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  41135. return Math.max(k, 3);
  41136. }
  41137. }
  41138. return Math.max(v, 3);
  41139. };
  41140. /**
  41141. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  41142. * @param x The point on the Gaussian distribution to sample.
  41143. * @return the value of the Gaussian function at x.
  41144. */
  41145. BlurPostProcess.prototype._gaussianWeight = function (x) {
  41146. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  41147. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  41148. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  41149. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  41150. // truncated at around 1.3% of peak strength.
  41151. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  41152. var sigma = (1 / 3);
  41153. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  41154. var exponent = -((x * x) / (2.0 * sigma * sigma));
  41155. var weight = (1.0 / denominator) * Math.exp(exponent);
  41156. return weight;
  41157. };
  41158. /**
  41159. * Generates a string that can be used as a floating point number in GLSL.
  41160. * @param x Value to print.
  41161. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  41162. * @return GLSL float string.
  41163. */
  41164. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  41165. if (decimalFigures === void 0) { decimalFigures = 8; }
  41166. return x.toFixed(decimalFigures).replace(/0+$/, '');
  41167. };
  41168. return BlurPostProcess;
  41169. }(BABYLON.PostProcess));
  41170. BABYLON.BlurPostProcess = BlurPostProcess;
  41171. })(BABYLON || (BABYLON = {}));
  41172. //# sourceMappingURL=babylon.blurPostProcess.js.map
  41173. var BABYLON;
  41174. (function (BABYLON) {
  41175. var FxaaPostProcess = (function (_super) {
  41176. __extends(FxaaPostProcess, _super);
  41177. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41178. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41179. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  41180. _this.onApplyObservable.add(function (effect) {
  41181. var texelSize = _this.texelSize;
  41182. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  41183. });
  41184. return _this;
  41185. }
  41186. return FxaaPostProcess;
  41187. }(BABYLON.PostProcess));
  41188. BABYLON.FxaaPostProcess = FxaaPostProcess;
  41189. })(BABYLON || (BABYLON = {}));
  41190. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  41191. var BABYLON;
  41192. (function (BABYLON) {
  41193. var HighlightsPostProcess = (function (_super) {
  41194. __extends(HighlightsPostProcess, _super);
  41195. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41196. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41197. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  41198. }
  41199. return HighlightsPostProcess;
  41200. }(BABYLON.PostProcess));
  41201. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  41202. })(BABYLON || (BABYLON = {}));
  41203. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  41204. var BABYLON;
  41205. (function (BABYLON) {
  41206. var ImageProcessingPostProcess = (function (_super) {
  41207. __extends(ImageProcessingPostProcess, _super);
  41208. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41209. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41210. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  41211. _this._fromLinearSpace = true;
  41212. /**
  41213. * Defines cache preventing GC.
  41214. */
  41215. _this._defines = {
  41216. IMAGEPROCESSING: false,
  41217. VIGNETTE: false,
  41218. VIGNETTEBLENDMODEMULTIPLY: false,
  41219. VIGNETTEBLENDMODEOPAQUE: false,
  41220. TONEMAPPING: false,
  41221. CONTRAST: false,
  41222. COLORCURVES: false,
  41223. COLORGRADING: false,
  41224. FROMLINEARSPACE: false,
  41225. SAMPLER3DGREENDEPTH: false,
  41226. SAMPLER3DBGRMAP: false,
  41227. IMAGEPROCESSINGPOSTPROCESS: false,
  41228. EXPOSURE: false,
  41229. };
  41230. // Setup the default processing configuration to the scene.
  41231. _this._attachImageProcessingConfiguration(null, true);
  41232. _this.imageProcessingConfiguration.applyByPostProcess = true;
  41233. _this.onApply = function (effect) {
  41234. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  41235. };
  41236. return _this;
  41237. }
  41238. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  41239. /**
  41240. * Gets the image processing configuration used either in this material.
  41241. */
  41242. get: function () {
  41243. return this._imageProcessingConfiguration;
  41244. },
  41245. /**
  41246. * Sets the Default image processing configuration used either in the this material.
  41247. *
  41248. * If sets to null, the scene one is in use.
  41249. */
  41250. set: function (value) {
  41251. this._attachImageProcessingConfiguration(value);
  41252. },
  41253. enumerable: true,
  41254. configurable: true
  41255. });
  41256. /**
  41257. * Attaches a new image processing configuration to the PBR Material.
  41258. * @param configuration
  41259. */
  41260. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  41261. var _this = this;
  41262. if (doNotBuild === void 0) { doNotBuild = false; }
  41263. if (configuration === this._imageProcessingConfiguration) {
  41264. return;
  41265. }
  41266. // Detaches observer.
  41267. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41268. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41269. }
  41270. // Pick the scene configuration if needed.
  41271. if (!configuration) {
  41272. var camera = this.getCamera();
  41273. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  41274. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  41275. }
  41276. else {
  41277. this._imageProcessingConfiguration = configuration;
  41278. }
  41279. // Attaches observer.
  41280. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41281. _this._updateParameters();
  41282. });
  41283. // Ensure the effect will be rebuilt.
  41284. if (!doNotBuild) {
  41285. this._updateParameters();
  41286. }
  41287. };
  41288. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  41289. /**
  41290. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  41291. */
  41292. get: function () {
  41293. return this.imageProcessingConfiguration.colorCurves;
  41294. },
  41295. /**
  41296. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  41297. */
  41298. set: function (value) {
  41299. this.imageProcessingConfiguration.colorCurves = value;
  41300. },
  41301. enumerable: true,
  41302. configurable: true
  41303. });
  41304. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  41305. /**
  41306. * Gets wether the color curves effect is enabled.
  41307. */
  41308. get: function () {
  41309. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41310. },
  41311. /**
  41312. * Sets wether the color curves effect is enabled.
  41313. */
  41314. set: function (value) {
  41315. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41316. },
  41317. enumerable: true,
  41318. configurable: true
  41319. });
  41320. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  41321. /**
  41322. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  41323. */
  41324. get: function () {
  41325. return this.imageProcessingConfiguration.colorGradingTexture;
  41326. },
  41327. /**
  41328. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  41329. */
  41330. set: function (value) {
  41331. this.imageProcessingConfiguration.colorGradingTexture = value;
  41332. },
  41333. enumerable: true,
  41334. configurable: true
  41335. });
  41336. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  41337. /**
  41338. * Gets wether the color grading effect is enabled.
  41339. */
  41340. get: function () {
  41341. return this.imageProcessingConfiguration.colorGradingEnabled;
  41342. },
  41343. /**
  41344. * Gets wether the color grading effect is enabled.
  41345. */
  41346. set: function (value) {
  41347. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41348. },
  41349. enumerable: true,
  41350. configurable: true
  41351. });
  41352. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  41353. /**
  41354. * Gets exposure used in the effect.
  41355. */
  41356. get: function () {
  41357. return this.imageProcessingConfiguration.exposure;
  41358. },
  41359. /**
  41360. * Sets exposure used in the effect.
  41361. */
  41362. set: function (value) {
  41363. this.imageProcessingConfiguration.exposure = value;
  41364. },
  41365. enumerable: true,
  41366. configurable: true
  41367. });
  41368. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  41369. /**
  41370. * Gets wether tonemapping is enabled or not.
  41371. */
  41372. get: function () {
  41373. return this._imageProcessingConfiguration.toneMappingEnabled;
  41374. },
  41375. /**
  41376. * Sets wether tonemapping is enabled or not
  41377. */
  41378. set: function (value) {
  41379. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41380. },
  41381. enumerable: true,
  41382. configurable: true
  41383. });
  41384. ;
  41385. ;
  41386. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  41387. /**
  41388. * Gets contrast used in the effect.
  41389. */
  41390. get: function () {
  41391. return this.imageProcessingConfiguration.contrast;
  41392. },
  41393. /**
  41394. * Sets contrast used in the effect.
  41395. */
  41396. set: function (value) {
  41397. this.imageProcessingConfiguration.contrast = value;
  41398. },
  41399. enumerable: true,
  41400. configurable: true
  41401. });
  41402. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  41403. /**
  41404. * Gets Vignette stretch size.
  41405. */
  41406. get: function () {
  41407. return this.imageProcessingConfiguration.vignetteStretch;
  41408. },
  41409. /**
  41410. * Sets Vignette stretch size.
  41411. */
  41412. set: function (value) {
  41413. this.imageProcessingConfiguration.vignetteStretch = value;
  41414. },
  41415. enumerable: true,
  41416. configurable: true
  41417. });
  41418. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  41419. /**
  41420. * Gets Vignette centre X Offset.
  41421. */
  41422. get: function () {
  41423. return this.imageProcessingConfiguration.vignetteCentreX;
  41424. },
  41425. /**
  41426. * Sets Vignette centre X Offset.
  41427. */
  41428. set: function (value) {
  41429. this.imageProcessingConfiguration.vignetteCentreX = value;
  41430. },
  41431. enumerable: true,
  41432. configurable: true
  41433. });
  41434. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  41435. /**
  41436. * Gets Vignette centre Y Offset.
  41437. */
  41438. get: function () {
  41439. return this.imageProcessingConfiguration.vignetteCentreY;
  41440. },
  41441. /**
  41442. * Sets Vignette centre Y Offset.
  41443. */
  41444. set: function (value) {
  41445. this.imageProcessingConfiguration.vignetteCentreY = value;
  41446. },
  41447. enumerable: true,
  41448. configurable: true
  41449. });
  41450. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  41451. /**
  41452. * Gets Vignette weight or intensity of the vignette effect.
  41453. */
  41454. get: function () {
  41455. return this.imageProcessingConfiguration.vignetteWeight;
  41456. },
  41457. /**
  41458. * Sets Vignette weight or intensity of the vignette effect.
  41459. */
  41460. set: function (value) {
  41461. this.imageProcessingConfiguration.vignetteWeight = value;
  41462. },
  41463. enumerable: true,
  41464. configurable: true
  41465. });
  41466. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  41467. /**
  41468. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41469. * if vignetteEnabled is set to true.
  41470. */
  41471. get: function () {
  41472. return this.imageProcessingConfiguration.vignetteColor;
  41473. },
  41474. /**
  41475. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41476. * if vignetteEnabled is set to true.
  41477. */
  41478. set: function (value) {
  41479. this.imageProcessingConfiguration.vignetteColor = value;
  41480. },
  41481. enumerable: true,
  41482. configurable: true
  41483. });
  41484. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  41485. /**
  41486. * Gets Camera field of view used by the Vignette effect.
  41487. */
  41488. get: function () {
  41489. return this.imageProcessingConfiguration.vignetteCameraFov;
  41490. },
  41491. /**
  41492. * Sets Camera field of view used by the Vignette effect.
  41493. */
  41494. set: function (value) {
  41495. this.imageProcessingConfiguration.vignetteCameraFov = value;
  41496. },
  41497. enumerable: true,
  41498. configurable: true
  41499. });
  41500. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  41501. /**
  41502. * Gets the vignette blend mode allowing different kind of effect.
  41503. */
  41504. get: function () {
  41505. return this.imageProcessingConfiguration.vignetteBlendMode;
  41506. },
  41507. /**
  41508. * Sets the vignette blend mode allowing different kind of effect.
  41509. */
  41510. set: function (value) {
  41511. this.imageProcessingConfiguration.vignetteBlendMode = value;
  41512. },
  41513. enumerable: true,
  41514. configurable: true
  41515. });
  41516. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  41517. /**
  41518. * Gets wether the vignette effect is enabled.
  41519. */
  41520. get: function () {
  41521. return this.imageProcessingConfiguration.vignetteEnabled;
  41522. },
  41523. /**
  41524. * Sets wether the vignette effect is enabled.
  41525. */
  41526. set: function (value) {
  41527. this.imageProcessingConfiguration.vignetteEnabled = value;
  41528. },
  41529. enumerable: true,
  41530. configurable: true
  41531. });
  41532. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  41533. /**
  41534. * Gets wether the input of the processing is in Gamma or Linear Space.
  41535. */
  41536. get: function () {
  41537. return this._fromLinearSpace;
  41538. },
  41539. /**
  41540. * Sets wether the input of the processing is in Gamma or Linear Space.
  41541. */
  41542. set: function (value) {
  41543. if (this._fromLinearSpace === value) {
  41544. return;
  41545. }
  41546. this._fromLinearSpace = value;
  41547. this._updateParameters();
  41548. },
  41549. enumerable: true,
  41550. configurable: true
  41551. });
  41552. ImageProcessingPostProcess.prototype.getClassName = function () {
  41553. return "ImageProcessingPostProcess";
  41554. };
  41555. ImageProcessingPostProcess.prototype._updateParameters = function () {
  41556. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  41557. this.imageProcessingConfiguration.prepareDefines(this._defines);
  41558. var defines = "";
  41559. for (var define in this._defines) {
  41560. if (this._defines[define]) {
  41561. defines += "#define " + define + ";\r\n";
  41562. }
  41563. }
  41564. var samplers = ["textureSampler"];
  41565. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  41566. var uniforms = ["scale"];
  41567. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  41568. this.updateEffect(defines, uniforms, samplers);
  41569. };
  41570. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  41571. _super.prototype.dispose.call(this, camera);
  41572. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41573. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41574. }
  41575. this.imageProcessingConfiguration.applyByPostProcess = false;
  41576. };
  41577. __decorate([
  41578. BABYLON.serialize()
  41579. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  41580. return ImageProcessingPostProcess;
  41581. }(BABYLON.PostProcess));
  41582. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  41583. })(BABYLON || (BABYLON = {}));
  41584. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  41585. var BABYLON;
  41586. (function (BABYLON) {
  41587. /**
  41588. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41589. * It can help converting any input color in a desired output one. This can then be used to create effects
  41590. * from sepia, black and white to sixties or futuristic rendering...
  41591. *
  41592. * The only supported format is currently 3dl.
  41593. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41594. */
  41595. var ColorGradingTexture = (function (_super) {
  41596. __extends(ColorGradingTexture, _super);
  41597. /**
  41598. * Instantiates a ColorGradingTexture from the following parameters.
  41599. *
  41600. * @param url The location of the color gradind data (currently only supporting 3dl)
  41601. * @param scene The scene the texture will be used in
  41602. */
  41603. function ColorGradingTexture(url, scene) {
  41604. var _this = _super.call(this, scene) || this;
  41605. if (!url) {
  41606. return _this;
  41607. }
  41608. _this._textureMatrix = BABYLON.Matrix.Identity();
  41609. _this.name = url;
  41610. _this.url = url;
  41611. _this.hasAlpha = false;
  41612. _this.isCube = false;
  41613. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41614. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41615. _this.anisotropicFilteringLevel = 1;
  41616. _this._texture = _this._getFromCache(url, true);
  41617. if (!_this._texture) {
  41618. if (!scene.useDelayedTextureLoading) {
  41619. _this.loadTexture();
  41620. }
  41621. else {
  41622. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41623. }
  41624. }
  41625. return _this;
  41626. }
  41627. /**
  41628. * Returns the texture matrix used in most of the material.
  41629. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41630. */
  41631. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41632. return this._textureMatrix;
  41633. };
  41634. /**
  41635. * Occurs when the file being loaded is a .3dl LUT file.
  41636. */
  41637. ColorGradingTexture.prototype.load3dlTexture = function () {
  41638. var _this = this;
  41639. var mipLevels = 0;
  41640. var floatArrayView = null;
  41641. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41642. this._texture = texture;
  41643. var callback = function (text) {
  41644. var data;
  41645. var tempData;
  41646. var line;
  41647. var lines = text.split('\n');
  41648. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41649. var maxColor = 0;
  41650. for (var i = 0; i < lines.length; i++) {
  41651. line = lines[i];
  41652. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41653. continue;
  41654. if (line.indexOf('#') === 0)
  41655. continue;
  41656. var words = line.split(" ");
  41657. if (size === 0) {
  41658. // Number of space + one
  41659. size = words.length;
  41660. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41661. tempData = new Float32Array(size * size * size * 4);
  41662. continue;
  41663. }
  41664. if (size != 0) {
  41665. var r = Math.max(parseInt(words[0]), 0);
  41666. var g = Math.max(parseInt(words[1]), 0);
  41667. var b = Math.max(parseInt(words[2]), 0);
  41668. maxColor = Math.max(r, maxColor);
  41669. maxColor = Math.max(g, maxColor);
  41670. maxColor = Math.max(b, maxColor);
  41671. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41672. tempData[pixelStorageIndex + 0] = r;
  41673. tempData[pixelStorageIndex + 1] = g;
  41674. tempData[pixelStorageIndex + 2] = b;
  41675. pixelIndexSlice++;
  41676. if (pixelIndexSlice % size == 0) {
  41677. pixelIndexH++;
  41678. pixelIndexSlice = 0;
  41679. if (pixelIndexH % size == 0) {
  41680. pixelIndexW++;
  41681. pixelIndexH = 0;
  41682. }
  41683. }
  41684. }
  41685. }
  41686. for (var i = 0; i < tempData.length; i++) {
  41687. if (i > 0 && (i + 1) % 4 === 0) {
  41688. data[i] = 255;
  41689. }
  41690. else {
  41691. var value = tempData[i];
  41692. data[i] = (value / maxColor * 255);
  41693. }
  41694. }
  41695. texture.updateSize(size * size, size);
  41696. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41697. };
  41698. BABYLON.Tools.LoadFile(this.url, callback);
  41699. return this._texture;
  41700. };
  41701. /**
  41702. * Starts the loading process of the texture.
  41703. */
  41704. ColorGradingTexture.prototype.loadTexture = function () {
  41705. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41706. this.load3dlTexture();
  41707. }
  41708. };
  41709. /**
  41710. * Clones the color gradind texture.
  41711. */
  41712. ColorGradingTexture.prototype.clone = function () {
  41713. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41714. // Base texture
  41715. newTexture.level = this.level;
  41716. return newTexture;
  41717. };
  41718. /**
  41719. * Called during delayed load for textures.
  41720. */
  41721. ColorGradingTexture.prototype.delayLoad = function () {
  41722. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41723. return;
  41724. }
  41725. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41726. this._texture = this._getFromCache(this.url, true);
  41727. if (!this._texture) {
  41728. this.loadTexture();
  41729. }
  41730. };
  41731. /**
  41732. * Parses a color grading texture serialized by Babylon.
  41733. * @param parsedTexture The texture information being parsedTexture
  41734. * @param scene The scene to load the texture in
  41735. * @param rootUrl The root url of the data assets to load
  41736. * @return A color gradind texture
  41737. */
  41738. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41739. var texture = null;
  41740. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41741. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  41742. texture.name = parsedTexture.name;
  41743. texture.level = parsedTexture.level;
  41744. }
  41745. return texture;
  41746. };
  41747. /**
  41748. * Serializes the LUT texture to json format.
  41749. */
  41750. ColorGradingTexture.prototype.serialize = function () {
  41751. if (!this.name) {
  41752. return null;
  41753. }
  41754. var serializationObject = {};
  41755. serializationObject.name = this.name;
  41756. serializationObject.level = this.level;
  41757. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41758. return serializationObject;
  41759. };
  41760. /**
  41761. * Empty line regex stored for GC.
  41762. */
  41763. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41764. return ColorGradingTexture;
  41765. }(BABYLON.BaseTexture));
  41766. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41767. })(BABYLON || (BABYLON = {}));
  41768. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41769. var BABYLON;
  41770. (function (BABYLON) {
  41771. /**
  41772. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41773. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41774. * 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;
  41775. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41776. */
  41777. var ColorCurves = (function () {
  41778. function ColorCurves() {
  41779. this._dirty = true;
  41780. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41781. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41782. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41783. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41784. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41785. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41786. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41787. this._globalHue = 30;
  41788. this._globalDensity = 0;
  41789. this._globalSaturation = 0;
  41790. this._globalExposure = 0;
  41791. this._highlightsHue = 30;
  41792. this._highlightsDensity = 0;
  41793. this._highlightsSaturation = 0;
  41794. this._highlightsExposure = 0;
  41795. this._midtonesHue = 30;
  41796. this._midtonesDensity = 0;
  41797. this._midtonesSaturation = 0;
  41798. this._midtonesExposure = 0;
  41799. this._shadowsHue = 30;
  41800. this._shadowsDensity = 0;
  41801. this._shadowsSaturation = 0;
  41802. this._shadowsExposure = 0;
  41803. }
  41804. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41805. /**
  41806. * Gets the global Hue value.
  41807. * 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).
  41808. */
  41809. get: function () {
  41810. return this._globalHue;
  41811. },
  41812. /**
  41813. * Sets the global Hue value.
  41814. * 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).
  41815. */
  41816. set: function (value) {
  41817. this._globalHue = value;
  41818. this._dirty = true;
  41819. },
  41820. enumerable: true,
  41821. configurable: true
  41822. });
  41823. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41824. /**
  41825. * Gets the global Density value.
  41826. * 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.
  41827. * Values less than zero provide a filter of opposite hue.
  41828. */
  41829. get: function () {
  41830. return this._globalDensity;
  41831. },
  41832. /**
  41833. * Sets the global Density value.
  41834. * 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.
  41835. * Values less than zero provide a filter of opposite hue.
  41836. */
  41837. set: function (value) {
  41838. this._globalDensity = value;
  41839. this._dirty = true;
  41840. },
  41841. enumerable: true,
  41842. configurable: true
  41843. });
  41844. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41845. /**
  41846. * Gets the global Saturation value.
  41847. * 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.
  41848. */
  41849. get: function () {
  41850. return this._globalSaturation;
  41851. },
  41852. /**
  41853. * Sets the global Saturation value.
  41854. * 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.
  41855. */
  41856. set: function (value) {
  41857. this._globalSaturation = value;
  41858. this._dirty = true;
  41859. },
  41860. enumerable: true,
  41861. configurable: true
  41862. });
  41863. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41864. /**
  41865. * Gets the highlights Hue value.
  41866. * 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).
  41867. */
  41868. get: function () {
  41869. return this._highlightsHue;
  41870. },
  41871. /**
  41872. * Sets the highlights Hue value.
  41873. * 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).
  41874. */
  41875. set: function (value) {
  41876. this._highlightsHue = value;
  41877. this._dirty = true;
  41878. },
  41879. enumerable: true,
  41880. configurable: true
  41881. });
  41882. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41883. /**
  41884. * Gets the highlights Density value.
  41885. * 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.
  41886. * Values less than zero provide a filter of opposite hue.
  41887. */
  41888. get: function () {
  41889. return this._highlightsDensity;
  41890. },
  41891. /**
  41892. * Sets the highlights Density value.
  41893. * 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.
  41894. * Values less than zero provide a filter of opposite hue.
  41895. */
  41896. set: function (value) {
  41897. this._highlightsDensity = value;
  41898. this._dirty = true;
  41899. },
  41900. enumerable: true,
  41901. configurable: true
  41902. });
  41903. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41904. /**
  41905. * Gets the highlights Saturation value.
  41906. * 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.
  41907. */
  41908. get: function () {
  41909. return this._highlightsSaturation;
  41910. },
  41911. /**
  41912. * Sets the highlights Saturation value.
  41913. * 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.
  41914. */
  41915. set: function (value) {
  41916. this._highlightsSaturation = value;
  41917. this._dirty = true;
  41918. },
  41919. enumerable: true,
  41920. configurable: true
  41921. });
  41922. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41923. /**
  41924. * Gets the highlights Exposure value.
  41925. * 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.
  41926. */
  41927. get: function () {
  41928. return this._highlightsExposure;
  41929. },
  41930. /**
  41931. * Sets the highlights Exposure value.
  41932. * 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.
  41933. */
  41934. set: function (value) {
  41935. this._highlightsExposure = value;
  41936. this._dirty = true;
  41937. },
  41938. enumerable: true,
  41939. configurable: true
  41940. });
  41941. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41942. /**
  41943. * Gets the midtones Hue value.
  41944. * 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).
  41945. */
  41946. get: function () {
  41947. return this._midtonesHue;
  41948. },
  41949. /**
  41950. * Sets the midtones Hue value.
  41951. * 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).
  41952. */
  41953. set: function (value) {
  41954. this._midtonesHue = value;
  41955. this._dirty = true;
  41956. },
  41957. enumerable: true,
  41958. configurable: true
  41959. });
  41960. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41961. /**
  41962. * Gets the midtones Density value.
  41963. * 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.
  41964. * Values less than zero provide a filter of opposite hue.
  41965. */
  41966. get: function () {
  41967. return this._midtonesDensity;
  41968. },
  41969. /**
  41970. * Sets the midtones Density value.
  41971. * 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.
  41972. * Values less than zero provide a filter of opposite hue.
  41973. */
  41974. set: function (value) {
  41975. this._midtonesDensity = value;
  41976. this._dirty = true;
  41977. },
  41978. enumerable: true,
  41979. configurable: true
  41980. });
  41981. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41982. /**
  41983. * Gets the midtones Saturation value.
  41984. * 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.
  41985. */
  41986. get: function () {
  41987. return this._midtonesSaturation;
  41988. },
  41989. /**
  41990. * Sets the midtones Saturation value.
  41991. * 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.
  41992. */
  41993. set: function (value) {
  41994. this._midtonesSaturation = value;
  41995. this._dirty = true;
  41996. },
  41997. enumerable: true,
  41998. configurable: true
  41999. });
  42000. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  42001. /**
  42002. * Gets the midtones Exposure value.
  42003. * 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.
  42004. */
  42005. get: function () {
  42006. return this._midtonesExposure;
  42007. },
  42008. /**
  42009. * Sets the midtones Exposure value.
  42010. * 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.
  42011. */
  42012. set: function (value) {
  42013. this._midtonesExposure = value;
  42014. this._dirty = true;
  42015. },
  42016. enumerable: true,
  42017. configurable: true
  42018. });
  42019. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42020. /**
  42021. * Gets the shadows Hue value.
  42022. * 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).
  42023. */
  42024. get: function () {
  42025. return this._shadowsHue;
  42026. },
  42027. /**
  42028. * Sets the shadows Hue value.
  42029. * 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).
  42030. */
  42031. set: function (value) {
  42032. this._shadowsHue = value;
  42033. this._dirty = true;
  42034. },
  42035. enumerable: true,
  42036. configurable: true
  42037. });
  42038. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42039. /**
  42040. * Gets the shadows Density value.
  42041. * 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.
  42042. * Values less than zero provide a filter of opposite hue.
  42043. */
  42044. get: function () {
  42045. return this._shadowsDensity;
  42046. },
  42047. /**
  42048. * Sets the shadows Density value.
  42049. * 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.
  42050. * Values less than zero provide a filter of opposite hue.
  42051. */
  42052. set: function (value) {
  42053. this._shadowsDensity = value;
  42054. this._dirty = true;
  42055. },
  42056. enumerable: true,
  42057. configurable: true
  42058. });
  42059. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42060. /**
  42061. * Gets the shadows Saturation value.
  42062. * 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.
  42063. */
  42064. get: function () {
  42065. return this._shadowsSaturation;
  42066. },
  42067. /**
  42068. * Sets the shadows Saturation value.
  42069. * 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.
  42070. */
  42071. set: function (value) {
  42072. this._shadowsSaturation = value;
  42073. this._dirty = true;
  42074. },
  42075. enumerable: true,
  42076. configurable: true
  42077. });
  42078. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42079. /**
  42080. * Gets the shadows Exposure value.
  42081. * 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.
  42082. */
  42083. get: function () {
  42084. return this._shadowsExposure;
  42085. },
  42086. /**
  42087. * Sets the shadows Exposure value.
  42088. * 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.
  42089. */
  42090. set: function (value) {
  42091. this._shadowsExposure = value;
  42092. this._dirty = true;
  42093. },
  42094. enumerable: true,
  42095. configurable: true
  42096. });
  42097. ColorCurves.prototype.getClassName = function () {
  42098. return "ColorCurves";
  42099. };
  42100. /**
  42101. * Binds the color curves to the shader.
  42102. * @param colorCurves The color curve to bind
  42103. * @param effect The effect to bind to
  42104. */
  42105. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42106. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42107. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42108. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42109. if (colorCurves._dirty) {
  42110. colorCurves._dirty = false;
  42111. // Fill in global info.
  42112. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42113. // Compute highlights info.
  42114. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42115. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42116. // Compute midtones info.
  42117. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42118. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42119. // Compute shadows info.
  42120. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42121. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42122. // Compute deltas (neutral is midtones).
  42123. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42124. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42125. }
  42126. if (effect) {
  42127. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42128. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42129. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42130. }
  42131. };
  42132. /**
  42133. * Prepare the list of uniforms associated with the ColorCurves effects.
  42134. * @param uniformsList The list of uniforms used in the effect
  42135. */
  42136. ColorCurves.PrepareUniforms = function (uniformsList) {
  42137. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42138. };
  42139. /**
  42140. * Returns color grading data based on a hue, density, saturation and exposure value.
  42141. * @param filterHue The hue of the color filter.
  42142. * @param filterDensity The density of the color filter.
  42143. * @param saturation The saturation.
  42144. * @param exposure The exposure.
  42145. * @param result The result data container.
  42146. */
  42147. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42148. if (hue == null) {
  42149. return;
  42150. }
  42151. hue = ColorCurves.clamp(hue, 0, 360);
  42152. density = ColorCurves.clamp(density, -100, 100);
  42153. saturation = ColorCurves.clamp(saturation, -100, 100);
  42154. exposure = ColorCurves.clamp(exposure, -100, 100);
  42155. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42156. // so that the maximum filter density is only 50% control. This provides fine control
  42157. // for small values and reasonable range.
  42158. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42159. density *= 0.5;
  42160. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42161. if (density < 0) {
  42162. density *= -1;
  42163. hue = (hue + 180) % 360;
  42164. }
  42165. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42166. result.scaleToRef(2, result);
  42167. result.a = 1 + 0.01 * saturation;
  42168. };
  42169. /**
  42170. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42171. * @param value The input slider value in range [-100,100].
  42172. * @returns Adjusted value.
  42173. */
  42174. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42175. value /= 100;
  42176. var x = Math.abs(value);
  42177. x = Math.pow(x, 2);
  42178. if (value < 0) {
  42179. x *= -1;
  42180. }
  42181. x *= 100;
  42182. return x;
  42183. };
  42184. /**
  42185. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42186. * @param hue The hue (H) input.
  42187. * @param saturation The saturation (S) input.
  42188. * @param brightness The brightness (B) input.
  42189. * @result An RGBA color represented as Vector4.
  42190. */
  42191. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42192. var h = ColorCurves.clamp(hue, 0, 360);
  42193. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42194. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42195. if (s === 0) {
  42196. result.r = v;
  42197. result.g = v;
  42198. result.b = v;
  42199. }
  42200. else {
  42201. // sector 0 to 5
  42202. h /= 60;
  42203. var i = Math.floor(h);
  42204. // fractional part of h
  42205. var f = h - i;
  42206. var p = v * (1 - s);
  42207. var q = v * (1 - s * f);
  42208. var t = v * (1 - s * (1 - f));
  42209. switch (i) {
  42210. case 0:
  42211. result.r = v;
  42212. result.g = t;
  42213. result.b = p;
  42214. break;
  42215. case 1:
  42216. result.r = q;
  42217. result.g = v;
  42218. result.b = p;
  42219. break;
  42220. case 2:
  42221. result.r = p;
  42222. result.g = v;
  42223. result.b = t;
  42224. break;
  42225. case 3:
  42226. result.r = p;
  42227. result.g = q;
  42228. result.b = v;
  42229. break;
  42230. case 4:
  42231. result.r = t;
  42232. result.g = p;
  42233. result.b = v;
  42234. break;
  42235. default:// case 5:
  42236. result.r = v;
  42237. result.g = p;
  42238. result.b = q;
  42239. break;
  42240. }
  42241. }
  42242. result.a = 1;
  42243. };
  42244. /**
  42245. * Returns a value clamped between min and max
  42246. * @param value The value to clamp
  42247. * @param min The minimum of value
  42248. * @param max The maximum of value
  42249. * @returns The clamped value.
  42250. */
  42251. ColorCurves.clamp = function (value, min, max) {
  42252. return Math.min(Math.max(value, min), max);
  42253. };
  42254. /**
  42255. * Clones the current color curve instance.
  42256. * @return The cloned curves
  42257. */
  42258. ColorCurves.prototype.clone = function () {
  42259. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42260. };
  42261. /**
  42262. * Serializes the current color curve instance to a json representation.
  42263. * @return a JSON representation
  42264. */
  42265. ColorCurves.prototype.serialize = function () {
  42266. return BABYLON.SerializationHelper.Serialize(this);
  42267. };
  42268. /**
  42269. * Parses the color curve from a json representation.
  42270. * @param source the JSON source to parse
  42271. * @return The parsed curves
  42272. */
  42273. ColorCurves.Parse = function (source) {
  42274. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42275. };
  42276. __decorate([
  42277. BABYLON.serialize()
  42278. ], ColorCurves.prototype, "_globalHue", void 0);
  42279. __decorate([
  42280. BABYLON.serialize()
  42281. ], ColorCurves.prototype, "_globalDensity", void 0);
  42282. __decorate([
  42283. BABYLON.serialize()
  42284. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42285. __decorate([
  42286. BABYLON.serialize()
  42287. ], ColorCurves.prototype, "_globalExposure", void 0);
  42288. __decorate([
  42289. BABYLON.serialize()
  42290. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42291. __decorate([
  42292. BABYLON.serialize()
  42293. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42294. __decorate([
  42295. BABYLON.serialize()
  42296. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42297. __decorate([
  42298. BABYLON.serialize()
  42299. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42300. __decorate([
  42301. BABYLON.serialize()
  42302. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42303. __decorate([
  42304. BABYLON.serialize()
  42305. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42306. __decorate([
  42307. BABYLON.serialize()
  42308. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42309. __decorate([
  42310. BABYLON.serialize()
  42311. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42312. return ColorCurves;
  42313. }());
  42314. BABYLON.ColorCurves = ColorCurves;
  42315. })(BABYLON || (BABYLON = {}));
  42316. //# sourceMappingURL=babylon.colorCurves.js.map
  42317. var BABYLON;
  42318. (function (BABYLON) {
  42319. var PostProcessRenderPipelineManager = (function () {
  42320. function PostProcessRenderPipelineManager() {
  42321. this._renderPipelines = {};
  42322. }
  42323. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  42324. this._renderPipelines[renderPipeline._name] = renderPipeline;
  42325. };
  42326. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  42327. var renderPipeline = this._renderPipelines[renderPipelineName];
  42328. if (!renderPipeline) {
  42329. return;
  42330. }
  42331. renderPipeline._attachCameras(cameras, unique);
  42332. };
  42333. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  42334. var renderPipeline = this._renderPipelines[renderPipelineName];
  42335. if (!renderPipeline) {
  42336. return;
  42337. }
  42338. renderPipeline._detachCameras(cameras);
  42339. };
  42340. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  42341. var renderPipeline = this._renderPipelines[renderPipelineName];
  42342. if (!renderPipeline) {
  42343. return;
  42344. }
  42345. renderPipeline._enableEffect(renderEffectName, cameras);
  42346. };
  42347. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  42348. var renderPipeline = this._renderPipelines[renderPipelineName];
  42349. if (!renderPipeline) {
  42350. return;
  42351. }
  42352. renderPipeline._disableEffect(renderEffectName, cameras);
  42353. };
  42354. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  42355. var renderPipeline = this._renderPipelines[renderPipelineName];
  42356. if (!renderPipeline) {
  42357. return;
  42358. }
  42359. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  42360. };
  42361. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  42362. var renderPipeline = this._renderPipelines[renderPipelineName];
  42363. if (!renderPipeline) {
  42364. return;
  42365. }
  42366. renderPipeline._disableDisplayOnlyPass(cameras);
  42367. };
  42368. PostProcessRenderPipelineManager.prototype.update = function () {
  42369. for (var renderPipelineName in this._renderPipelines) {
  42370. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  42371. var pipeline = this._renderPipelines[renderPipelineName];
  42372. if (!pipeline.isSupported) {
  42373. pipeline.dispose();
  42374. delete this._renderPipelines[renderPipelineName];
  42375. }
  42376. else {
  42377. pipeline._update();
  42378. }
  42379. }
  42380. }
  42381. };
  42382. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  42383. for (var renderPipelineName in this._renderPipelines) {
  42384. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  42385. var pipeline = this._renderPipelines[renderPipelineName];
  42386. pipeline._rebuild();
  42387. }
  42388. }
  42389. };
  42390. PostProcessRenderPipelineManager.prototype.dispose = function () {
  42391. for (var renderPipelineName in this._renderPipelines) {
  42392. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  42393. var pipeline = this._renderPipelines[renderPipelineName];
  42394. pipeline.dispose();
  42395. }
  42396. }
  42397. };
  42398. return PostProcessRenderPipelineManager;
  42399. }());
  42400. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  42401. })(BABYLON || (BABYLON = {}));
  42402. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  42403. var BABYLON;
  42404. (function (BABYLON) {
  42405. var PostProcessRenderPass = (function () {
  42406. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  42407. this._enabled = true;
  42408. this._refCount = 0;
  42409. this._name = name;
  42410. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  42411. this.setRenderList(renderList);
  42412. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  42413. this._renderTexture.onAfterRenderObservable.add(afterRender);
  42414. this._scene = scene;
  42415. this._renderList = renderList;
  42416. }
  42417. // private
  42418. PostProcessRenderPass.prototype._incRefCount = function () {
  42419. if (this._refCount === 0) {
  42420. this._scene.customRenderTargets.push(this._renderTexture);
  42421. }
  42422. return ++this._refCount;
  42423. };
  42424. PostProcessRenderPass.prototype._decRefCount = function () {
  42425. this._refCount--;
  42426. if (this._refCount <= 0) {
  42427. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  42428. }
  42429. return this._refCount;
  42430. };
  42431. PostProcessRenderPass.prototype._update = function () {
  42432. this.setRenderList(this._renderList);
  42433. };
  42434. // public
  42435. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  42436. this._renderTexture.renderList = renderList;
  42437. };
  42438. PostProcessRenderPass.prototype.getRenderTexture = function () {
  42439. return this._renderTexture;
  42440. };
  42441. return PostProcessRenderPass;
  42442. }());
  42443. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  42444. })(BABYLON || (BABYLON = {}));
  42445. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  42446. var BABYLON;
  42447. (function (BABYLON) {
  42448. var PostProcessRenderEffect = (function () {
  42449. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  42450. this._engine = engine;
  42451. this._name = name;
  42452. this._singleInstance = singleInstance || true;
  42453. this._getPostProcess = getPostProcess;
  42454. this._cameras = [];
  42455. this._indicesForCamera = [];
  42456. this._postProcesses = {};
  42457. this._renderPasses = {};
  42458. this._renderEffectAsPasses = {};
  42459. }
  42460. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  42461. get: function () {
  42462. for (var index in this._postProcesses) {
  42463. if (!this._postProcesses[index].isSupported) {
  42464. return false;
  42465. }
  42466. }
  42467. return true;
  42468. },
  42469. enumerable: true,
  42470. configurable: true
  42471. });
  42472. PostProcessRenderEffect.prototype._update = function () {
  42473. for (var renderPassName in this._renderPasses) {
  42474. this._renderPasses[renderPassName]._update();
  42475. }
  42476. };
  42477. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  42478. this._renderPasses[renderPass._name] = renderPass;
  42479. this._linkParameters();
  42480. };
  42481. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  42482. delete this._renderPasses[renderPass._name];
  42483. this._linkParameters();
  42484. };
  42485. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  42486. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  42487. this._linkParameters();
  42488. };
  42489. PostProcessRenderEffect.prototype.getPass = function (passName) {
  42490. for (var renderPassName in this._renderPasses) {
  42491. if (renderPassName === passName) {
  42492. return this._renderPasses[passName];
  42493. }
  42494. }
  42495. };
  42496. PostProcessRenderEffect.prototype.emptyPasses = function () {
  42497. this._renderPasses = {};
  42498. this._linkParameters();
  42499. };
  42500. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  42501. var cameraKey;
  42502. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42503. for (var i = 0; i < _cam.length; i++) {
  42504. var camera = _cam[i];
  42505. var cameraName = camera.name;
  42506. if (this._singleInstance) {
  42507. cameraKey = 0;
  42508. }
  42509. else {
  42510. cameraKey = cameraName;
  42511. }
  42512. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  42513. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  42514. if (!this._indicesForCamera[cameraName]) {
  42515. this._indicesForCamera[cameraName] = [];
  42516. }
  42517. this._indicesForCamera[cameraName].push(index);
  42518. if (this._cameras.indexOf(camera) === -1) {
  42519. this._cameras[cameraName] = camera;
  42520. }
  42521. for (var passName in this._renderPasses) {
  42522. this._renderPasses[passName]._incRefCount();
  42523. }
  42524. }
  42525. this._linkParameters();
  42526. };
  42527. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  42528. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42529. for (var i = 0; i < _cam.length; i++) {
  42530. var camera = _cam[i];
  42531. var cameraName = camera.name;
  42532. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42533. var index = this._cameras.indexOf(cameraName);
  42534. this._indicesForCamera.splice(index, 1);
  42535. this._cameras.splice(index, 1);
  42536. for (var passName in this._renderPasses) {
  42537. this._renderPasses[passName]._decRefCount();
  42538. }
  42539. }
  42540. };
  42541. PostProcessRenderEffect.prototype._enable = function (cameras) {
  42542. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42543. for (var i = 0; i < _cam.length; i++) {
  42544. var camera = _cam[i];
  42545. var cameraName = camera.name;
  42546. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  42547. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  42548. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  42549. }
  42550. }
  42551. for (var passName in this._renderPasses) {
  42552. this._renderPasses[passName]._incRefCount();
  42553. }
  42554. }
  42555. };
  42556. PostProcessRenderEffect.prototype._disable = function (cameras) {
  42557. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42558. for (var i = 0; i < _cam.length; i++) {
  42559. var camera = _cam[i];
  42560. var cameraName = camera.Name;
  42561. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42562. for (var passName in this._renderPasses) {
  42563. this._renderPasses[passName]._decRefCount();
  42564. }
  42565. }
  42566. };
  42567. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  42568. if (this._singleInstance) {
  42569. return this._postProcesses[0];
  42570. }
  42571. else {
  42572. return this._postProcesses[camera.name];
  42573. }
  42574. };
  42575. PostProcessRenderEffect.prototype._linkParameters = function () {
  42576. var _this = this;
  42577. for (var index in this._postProcesses) {
  42578. if (this.applyParameters) {
  42579. this.applyParameters(this._postProcesses[index]);
  42580. }
  42581. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  42582. _this._linkTextures(effect);
  42583. });
  42584. }
  42585. };
  42586. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  42587. for (var renderPassName in this._renderPasses) {
  42588. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  42589. }
  42590. for (var renderEffectName in this._renderEffectAsPasses) {
  42591. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  42592. }
  42593. };
  42594. return PostProcessRenderEffect;
  42595. }());
  42596. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  42597. })(BABYLON || (BABYLON = {}));
  42598. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  42599. var BABYLON;
  42600. (function (BABYLON) {
  42601. var PostProcessRenderPipeline = (function () {
  42602. function PostProcessRenderPipeline(engine, name) {
  42603. this._engine = engine;
  42604. this._name = name;
  42605. this._renderEffects = new Array();
  42606. this._renderEffectsForIsolatedPass = new Array();
  42607. this._cameras = [];
  42608. }
  42609. PostProcessRenderPipeline.prototype.getClassName = function () {
  42610. return "PostProcessRenderPipeline";
  42611. };
  42612. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  42613. get: function () {
  42614. for (var renderEffectName in this._renderEffects) {
  42615. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42616. if (!this._renderEffects[renderEffectName].isSupported) {
  42617. return false;
  42618. }
  42619. }
  42620. }
  42621. return true;
  42622. },
  42623. enumerable: true,
  42624. configurable: true
  42625. });
  42626. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  42627. this._renderEffects[renderEffect._name] = renderEffect;
  42628. };
  42629. // private
  42630. PostProcessRenderPipeline.prototype._rebuild = function () {
  42631. };
  42632. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  42633. var renderEffects = this._renderEffects[renderEffectName];
  42634. if (!renderEffects) {
  42635. return;
  42636. }
  42637. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42638. };
  42639. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  42640. var renderEffects = this._renderEffects[renderEffectName];
  42641. if (!renderEffects) {
  42642. return;
  42643. }
  42644. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42645. };
  42646. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  42647. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42648. var indicesToDelete = [];
  42649. var i;
  42650. for (i = 0; i < _cam.length; i++) {
  42651. var camera = _cam[i];
  42652. var cameraName = camera.name;
  42653. if (this._cameras.indexOf(camera) === -1) {
  42654. this._cameras[cameraName] = camera;
  42655. }
  42656. else if (unique) {
  42657. indicesToDelete.push(i);
  42658. }
  42659. }
  42660. for (i = 0; i < indicesToDelete.length; i++) {
  42661. cameras.splice(indicesToDelete[i], 1);
  42662. }
  42663. for (var renderEffectName in this._renderEffects) {
  42664. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42665. this._renderEffects[renderEffectName]._attachCameras(_cam);
  42666. }
  42667. }
  42668. };
  42669. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  42670. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42671. for (var renderEffectName in this._renderEffects) {
  42672. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42673. this._renderEffects[renderEffectName]._detachCameras(_cam);
  42674. }
  42675. }
  42676. for (var i = 0; i < _cam.length; i++) {
  42677. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  42678. }
  42679. };
  42680. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  42681. var _this = this;
  42682. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42683. var pass = null;
  42684. var renderEffectName;
  42685. for (renderEffectName in this._renderEffects) {
  42686. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42687. pass = this._renderEffects[renderEffectName].getPass(passName);
  42688. if (pass != null) {
  42689. break;
  42690. }
  42691. }
  42692. }
  42693. if (pass === null) {
  42694. return;
  42695. }
  42696. for (renderEffectName in this._renderEffects) {
  42697. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42698. this._renderEffects[renderEffectName]._disable(_cam);
  42699. }
  42700. }
  42701. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  42702. for (var i = 0; i < _cam.length; i++) {
  42703. var camera = _cam[i];
  42704. var cameraName = camera.name;
  42705. 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); });
  42706. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  42707. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  42708. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  42709. }
  42710. };
  42711. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  42712. var _this = this;
  42713. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42714. for (var i = 0; i < _cam.length; i++) {
  42715. var camera = _cam[i];
  42716. var cameraName = camera.name;
  42717. 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); });
  42718. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  42719. }
  42720. for (var renderEffectName in this._renderEffects) {
  42721. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42722. this._renderEffects[renderEffectName]._enable(_cam);
  42723. }
  42724. }
  42725. };
  42726. PostProcessRenderPipeline.prototype._update = function () {
  42727. for (var renderEffectName in this._renderEffects) {
  42728. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  42729. this._renderEffects[renderEffectName]._update();
  42730. }
  42731. }
  42732. for (var i = 0; i < this._cameras.length; i++) {
  42733. var cameraName = this._cameras[i].name;
  42734. if (this._renderEffectsForIsolatedPass[cameraName]) {
  42735. this._renderEffectsForIsolatedPass[cameraName]._update();
  42736. }
  42737. }
  42738. };
  42739. PostProcessRenderPipeline.prototype._reset = function () {
  42740. this._renderEffects = new Array();
  42741. this._renderEffectsForIsolatedPass = new Array();
  42742. };
  42743. PostProcessRenderPipeline.prototype.dispose = function () {
  42744. // Must be implemented by children
  42745. };
  42746. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  42747. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  42748. __decorate([
  42749. BABYLON.serialize()
  42750. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  42751. return PostProcessRenderPipeline;
  42752. }());
  42753. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  42754. })(BABYLON || (BABYLON = {}));
  42755. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  42756. var BABYLON;
  42757. (function (BABYLON) {
  42758. var DefaultRenderingPipeline = (function (_super) {
  42759. __extends(DefaultRenderingPipeline, _super);
  42760. /**
  42761. * @constructor
  42762. * @param {string} name - The rendering pipeline name
  42763. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  42764. * @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)
  42765. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  42766. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  42767. */
  42768. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  42769. if (automaticBuild === void 0) { automaticBuild = true; }
  42770. var _this = _super.call(this, scene.getEngine(), name) || this;
  42771. _this.PassPostProcessId = "PassPostProcessEffect";
  42772. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  42773. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  42774. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  42775. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  42776. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  42777. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  42778. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  42779. // IAnimatable
  42780. _this.animations = [];
  42781. // Values
  42782. _this._bloomEnabled = false;
  42783. _this._fxaaEnabled = false;
  42784. _this._imageProcessingEnabled = true;
  42785. _this._bloomScale = 0.6;
  42786. _this._buildAllowed = true;
  42787. /**
  42788. * Specifies the size of the bloom blur kernel, relative to the final output size
  42789. */
  42790. _this.bloomKernel = 64;
  42791. /**
  42792. * Specifies the weight of the bloom in the final rendering
  42793. */
  42794. _this._bloomWeight = 0.15;
  42795. _this._cameras = cameras || [];
  42796. _this._buildAllowed = automaticBuild;
  42797. // Initialize
  42798. _this._scene = scene;
  42799. var caps = _this._scene.getEngine().getCaps();
  42800. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  42801. // Misc
  42802. if (_this._hdr) {
  42803. if (caps.textureHalfFloatRender) {
  42804. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  42805. }
  42806. else if (caps.textureFloatRender) {
  42807. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42808. }
  42809. }
  42810. else {
  42811. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42812. }
  42813. // Attach
  42814. scene.postProcessRenderPipelineManager.addPipeline(_this);
  42815. _this._buildPipeline();
  42816. return _this;
  42817. }
  42818. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  42819. get: function () {
  42820. return this._bloomWeight;
  42821. },
  42822. set: function (value) {
  42823. if (this._bloomWeight === value) {
  42824. return;
  42825. }
  42826. this._bloomWeight = value;
  42827. if (this._hdr && this.copyBack) {
  42828. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  42829. }
  42830. },
  42831. enumerable: true,
  42832. configurable: true
  42833. });
  42834. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  42835. get: function () {
  42836. return this._bloomScale;
  42837. },
  42838. set: function (value) {
  42839. if (this._bloomScale === value) {
  42840. return;
  42841. }
  42842. this._bloomScale = value;
  42843. this._buildPipeline();
  42844. },
  42845. enumerable: true,
  42846. configurable: true
  42847. });
  42848. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  42849. get: function () {
  42850. return this._bloomEnabled;
  42851. },
  42852. set: function (enabled) {
  42853. if (this._bloomEnabled === enabled) {
  42854. return;
  42855. }
  42856. this._bloomEnabled = enabled;
  42857. this._buildPipeline();
  42858. },
  42859. enumerable: true,
  42860. configurable: true
  42861. });
  42862. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  42863. get: function () {
  42864. return this._fxaaEnabled;
  42865. },
  42866. set: function (enabled) {
  42867. if (this._fxaaEnabled === enabled) {
  42868. return;
  42869. }
  42870. this._fxaaEnabled = enabled;
  42871. this._buildPipeline();
  42872. },
  42873. enumerable: true,
  42874. configurable: true
  42875. });
  42876. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  42877. get: function () {
  42878. return this._imageProcessingEnabled;
  42879. },
  42880. set: function (enabled) {
  42881. if (this._imageProcessingEnabled === enabled) {
  42882. return;
  42883. }
  42884. this._imageProcessingEnabled = enabled;
  42885. this._buildPipeline();
  42886. },
  42887. enumerable: true,
  42888. configurable: true
  42889. });
  42890. /**
  42891. * Force the compilation of the entire pipeline.
  42892. */
  42893. DefaultRenderingPipeline.prototype.prepare = function () {
  42894. var previousState = this._buildAllowed;
  42895. this._buildAllowed = true;
  42896. this._buildPipeline();
  42897. this._buildAllowed = previousState;
  42898. };
  42899. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  42900. var _this = this;
  42901. if (!this._buildAllowed) {
  42902. return;
  42903. }
  42904. var engine = this._scene.getEngine();
  42905. this._disposePostProcesses();
  42906. this._reset();
  42907. if (this.bloomEnabled) {
  42908. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42909. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  42910. if (!this._hdr) {
  42911. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42912. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  42913. this.highlights.autoClear = false;
  42914. this.highlights.alwaysForcePOT = true;
  42915. }
  42916. 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);
  42917. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  42918. this.blurX.alwaysForcePOT = true;
  42919. this.blurX.autoClear = false;
  42920. this.blurX.onActivateObservable.add(function () {
  42921. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  42922. _this.blurX.kernel = _this.bloomKernel * dw;
  42923. });
  42924. 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);
  42925. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  42926. this.blurY.alwaysForcePOT = true;
  42927. this.blurY.autoClear = false;
  42928. this.blurY.onActivateObservable.add(function () {
  42929. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  42930. _this.blurY.kernel = _this.bloomKernel * dh;
  42931. });
  42932. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42933. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  42934. this.copyBack.alwaysForcePOT = true;
  42935. if (this._hdr) {
  42936. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  42937. var w = this.bloomWeight;
  42938. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  42939. }
  42940. else {
  42941. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  42942. }
  42943. this.copyBack.autoClear = false;
  42944. }
  42945. if (this._imageProcessingEnabled) {
  42946. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42947. if (this._hdr) {
  42948. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  42949. }
  42950. }
  42951. if (this.fxaaEnabled) {
  42952. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42953. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  42954. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  42955. }
  42956. else {
  42957. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42958. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  42959. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  42960. }
  42961. if (this.bloomEnabled) {
  42962. if (this._hdr) {
  42963. this.copyBack.shareOutputWith(this.blurX);
  42964. if (this.imageProcessing) {
  42965. this.imageProcessing.shareOutputWith(this.pass);
  42966. this.imageProcessing.autoClear = false;
  42967. }
  42968. else if (this.fxaa) {
  42969. this.fxaa.shareOutputWith(this.pass);
  42970. }
  42971. else {
  42972. this.finalMerge.shareOutputWith(this.pass);
  42973. }
  42974. }
  42975. else {
  42976. if (this.fxaa) {
  42977. this.fxaa.shareOutputWith(this.pass);
  42978. }
  42979. else {
  42980. this.finalMerge.shareOutputWith(this.pass);
  42981. }
  42982. }
  42983. }
  42984. if (this._cameras !== null) {
  42985. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  42986. }
  42987. };
  42988. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  42989. for (var i = 0; i < this._cameras.length; i++) {
  42990. var camera = this._cameras[i];
  42991. if (this.pass) {
  42992. this.pass.dispose(camera);
  42993. }
  42994. if (this.highlights) {
  42995. this.highlights.dispose(camera);
  42996. }
  42997. if (this.blurX) {
  42998. this.blurX.dispose(camera);
  42999. }
  43000. if (this.blurY) {
  43001. this.blurY.dispose(camera);
  43002. }
  43003. if (this.copyBack) {
  43004. this.copyBack.dispose(camera);
  43005. }
  43006. if (this.imageProcessing) {
  43007. this.imageProcessing.dispose(camera);
  43008. }
  43009. if (this.fxaa) {
  43010. this.fxaa.dispose(camera);
  43011. }
  43012. if (this.finalMerge) {
  43013. this.finalMerge.dispose(camera);
  43014. }
  43015. }
  43016. this.pass = null;
  43017. this.highlights = null;
  43018. this.blurX = null;
  43019. this.blurY = null;
  43020. this.copyBack = null;
  43021. this.imageProcessing = null;
  43022. this.fxaa = null;
  43023. this.finalMerge = null;
  43024. };
  43025. // Dispose
  43026. DefaultRenderingPipeline.prototype.dispose = function () {
  43027. this._disposePostProcesses();
  43028. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  43029. _super.prototype.dispose.call(this);
  43030. };
  43031. // Serialize rendering pipeline
  43032. DefaultRenderingPipeline.prototype.serialize = function () {
  43033. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43034. serializationObject.customType = "DefaultRenderingPipeline";
  43035. return serializationObject;
  43036. };
  43037. // Parse serialized pipeline
  43038. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  43039. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  43040. };
  43041. __decorate([
  43042. BABYLON.serialize()
  43043. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  43044. __decorate([
  43045. BABYLON.serialize()
  43046. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  43047. __decorate([
  43048. BABYLON.serialize()
  43049. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  43050. __decorate([
  43051. BABYLON.serialize()
  43052. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  43053. __decorate([
  43054. BABYLON.serialize()
  43055. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  43056. __decorate([
  43057. BABYLON.serialize()
  43058. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  43059. __decorate([
  43060. BABYLON.serialize()
  43061. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  43062. __decorate([
  43063. BABYLON.serialize()
  43064. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  43065. return DefaultRenderingPipeline;
  43066. }(BABYLON.PostProcessRenderPipeline));
  43067. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  43068. })(BABYLON || (BABYLON = {}));
  43069. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  43070. var BABYLON;
  43071. (function (BABYLON) {
  43072. /**
  43073. * This groups together the common properties used for image processing either in direct forward pass
  43074. * or through post processing effect depending on the use of the image processing pipeline in your scene
  43075. * or not.
  43076. */
  43077. var ImageProcessingConfiguration = (function () {
  43078. function ImageProcessingConfiguration() {
  43079. /**
  43080. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  43081. */
  43082. this.colorCurves = new BABYLON.ColorCurves();
  43083. this._colorCurvesEnabled = false;
  43084. this._colorGradingEnabled = false;
  43085. this._colorGradingWithGreenDepth = false;
  43086. this._colorGradingBGR = false;
  43087. this._exposure = 1.0;
  43088. this._toneMappingEnabled = false;
  43089. this._contrast = 1.0;
  43090. /**
  43091. * Vignette stretch size.
  43092. */
  43093. this.vignetteStretch = 0;
  43094. /**
  43095. * Vignette centre X Offset.
  43096. */
  43097. this.vignetteCentreX = 0;
  43098. /**
  43099. * Vignette centre Y Offset.
  43100. */
  43101. this.vignetteCentreY = 0;
  43102. /**
  43103. * Vignette weight or intensity of the vignette effect.
  43104. */
  43105. this.vignetteWeight = 1.5;
  43106. /**
  43107. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  43108. * if vignetteEnabled is set to true.
  43109. */
  43110. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  43111. /**
  43112. * Camera field of view used by the Vignette effect.
  43113. */
  43114. this.vignetteCameraFov = 0.5;
  43115. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  43116. this._vignetteEnabled = false;
  43117. this._applyByPostProcess = false;
  43118. /**
  43119. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  43120. * @type {BABYLON.Observable}
  43121. */
  43122. this.onUpdateParameters = new BABYLON.Observable();
  43123. }
  43124. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  43125. /**
  43126. * Gets wether the color curves effect is enabled.
  43127. */
  43128. get: function () {
  43129. return this._colorCurvesEnabled;
  43130. },
  43131. /**
  43132. * Sets wether the color curves effect is enabled.
  43133. */
  43134. set: function (value) {
  43135. if (this._colorCurvesEnabled === value) {
  43136. return;
  43137. }
  43138. this._colorCurvesEnabled = value;
  43139. this._updateParameters();
  43140. },
  43141. enumerable: true,
  43142. configurable: true
  43143. });
  43144. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  43145. /**
  43146. * Gets wether the color grading effect is enabled.
  43147. */
  43148. get: function () {
  43149. return this._colorGradingEnabled;
  43150. },
  43151. /**
  43152. * Sets wether the color grading effect is enabled.
  43153. */
  43154. set: function (value) {
  43155. if (this._colorGradingEnabled === value) {
  43156. return;
  43157. }
  43158. this._colorGradingEnabled = value;
  43159. this._updateParameters();
  43160. },
  43161. enumerable: true,
  43162. configurable: true
  43163. });
  43164. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  43165. /**
  43166. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  43167. */
  43168. get: function () {
  43169. return this._colorGradingWithGreenDepth;
  43170. },
  43171. /**
  43172. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  43173. */
  43174. set: function (value) {
  43175. if (this._colorGradingWithGreenDepth === value) {
  43176. return;
  43177. }
  43178. this._colorGradingWithGreenDepth = value;
  43179. this._updateParameters();
  43180. },
  43181. enumerable: true,
  43182. configurable: true
  43183. });
  43184. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  43185. /**
  43186. * Gets wether the color grading texture contains BGR values.
  43187. */
  43188. get: function () {
  43189. return this._colorGradingBGR;
  43190. },
  43191. /**
  43192. * Sets wether the color grading texture contains BGR values.
  43193. */
  43194. set: function (value) {
  43195. if (this._colorGradingBGR === value) {
  43196. return;
  43197. }
  43198. this._colorGradingBGR = value;
  43199. this._updateParameters();
  43200. },
  43201. enumerable: true,
  43202. configurable: true
  43203. });
  43204. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  43205. /**
  43206. * Gets the Exposure used in the effect.
  43207. */
  43208. get: function () {
  43209. return this._exposure;
  43210. },
  43211. /**
  43212. * Sets the Exposure used in the effect.
  43213. */
  43214. set: function (value) {
  43215. if (this._exposure === value) {
  43216. return;
  43217. }
  43218. this._exposure = value;
  43219. this._updateParameters();
  43220. },
  43221. enumerable: true,
  43222. configurable: true
  43223. });
  43224. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  43225. /**
  43226. * Gets wether the tone mapping effect is enabled.
  43227. */
  43228. get: function () {
  43229. return this._toneMappingEnabled;
  43230. },
  43231. /**
  43232. * Sets wether the tone mapping effect is enabled.
  43233. */
  43234. set: function (value) {
  43235. if (this._toneMappingEnabled === value) {
  43236. return;
  43237. }
  43238. this._toneMappingEnabled = value;
  43239. this._updateParameters();
  43240. },
  43241. enumerable: true,
  43242. configurable: true
  43243. });
  43244. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  43245. /**
  43246. * Gets the contrast used in the effect.
  43247. */
  43248. get: function () {
  43249. return this._contrast;
  43250. },
  43251. /**
  43252. * Sets the contrast used in the effect.
  43253. */
  43254. set: function (value) {
  43255. if (this._contrast === value) {
  43256. return;
  43257. }
  43258. this._contrast = value;
  43259. this._updateParameters();
  43260. },
  43261. enumerable: true,
  43262. configurable: true
  43263. });
  43264. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  43265. /**
  43266. * Gets the vignette blend mode allowing different kind of effect.
  43267. */
  43268. get: function () {
  43269. return this._vignetteBlendMode;
  43270. },
  43271. /**
  43272. * Sets the vignette blend mode allowing different kind of effect.
  43273. */
  43274. set: function (value) {
  43275. if (this._vignetteBlendMode === value) {
  43276. return;
  43277. }
  43278. this._vignetteBlendMode = value;
  43279. this._updateParameters();
  43280. },
  43281. enumerable: true,
  43282. configurable: true
  43283. });
  43284. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  43285. /**
  43286. * Gets wether the vignette effect is enabled.
  43287. */
  43288. get: function () {
  43289. return this._vignetteEnabled;
  43290. },
  43291. /**
  43292. * Sets wether the vignette effect is enabled.
  43293. */
  43294. set: function (value) {
  43295. if (this._vignetteEnabled === value) {
  43296. return;
  43297. }
  43298. this._vignetteEnabled = value;
  43299. this._updateParameters();
  43300. },
  43301. enumerable: true,
  43302. configurable: true
  43303. });
  43304. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  43305. /**
  43306. * Gets wether the image processing is applied through a post process or not.
  43307. */
  43308. get: function () {
  43309. return this._applyByPostProcess;
  43310. },
  43311. /**
  43312. * Sets wether the image processing is applied through a post process or not.
  43313. */
  43314. set: function (value) {
  43315. if (this._applyByPostProcess === value) {
  43316. return;
  43317. }
  43318. this._applyByPostProcess = value;
  43319. this._updateParameters();
  43320. },
  43321. enumerable: true,
  43322. configurable: true
  43323. });
  43324. /**
  43325. * Method called each time the image processing information changes requires to recompile the effect.
  43326. */
  43327. ImageProcessingConfiguration.prototype._updateParameters = function () {
  43328. this.onUpdateParameters.notifyObservers(this);
  43329. };
  43330. ImageProcessingConfiguration.prototype.getClassName = function () {
  43331. return "ImageProcessingConfiguration";
  43332. };
  43333. /**
  43334. * Prepare the list of uniforms associated with the Image Processing effects.
  43335. * @param uniformsList The list of uniforms used in the effect
  43336. * @param defines the list of defines currently in use
  43337. */
  43338. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  43339. if (defines.EXPOSURE) {
  43340. uniforms.push("exposureLinear");
  43341. }
  43342. if (defines.CONTRAST) {
  43343. uniforms.push("contrast");
  43344. }
  43345. if (defines.COLORGRADING) {
  43346. uniforms.push("colorTransformSettings");
  43347. }
  43348. if (defines.VIGNETTE) {
  43349. uniforms.push("vInverseScreenSize");
  43350. uniforms.push("vignetteSettings1");
  43351. uniforms.push("vignetteSettings2");
  43352. }
  43353. if (defines.COLORCURVES) {
  43354. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  43355. }
  43356. };
  43357. /**
  43358. * Prepare the list of samplers associated with the Image Processing effects.
  43359. * @param uniformsList The list of uniforms used in the effect
  43360. * @param defines the list of defines currently in use
  43361. */
  43362. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  43363. if (defines.COLORGRADING) {
  43364. samplersList.push("txColorTransform");
  43365. }
  43366. };
  43367. /**
  43368. * Prepare the list of defines associated to the shader.
  43369. * @param defines the list of defines to complete
  43370. */
  43371. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  43372. defines.VIGNETTE = this.vignetteEnabled;
  43373. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  43374. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  43375. defines.TONEMAPPING = this.toneMappingEnabled;
  43376. defines.CONTRAST = (this.contrast !== 1.0);
  43377. defines.EXPOSURE = (this.exposure !== 1.0);
  43378. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  43379. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  43380. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  43381. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  43382. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  43383. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  43384. };
  43385. /**
  43386. * Returns true if all the image processing information are ready.
  43387. */
  43388. ImageProcessingConfiguration.prototype.isReady = function () {
  43389. // Color Grading texure can not be none blocking.
  43390. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  43391. };
  43392. /**
  43393. * Binds the image processing to the shader.
  43394. * @param effect The effect to bind to
  43395. */
  43396. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  43397. if (aspectRatio === void 0) { aspectRatio = 1; }
  43398. // Color Curves
  43399. if (this._colorCurvesEnabled) {
  43400. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  43401. }
  43402. // Vignette
  43403. if (this._vignetteEnabled) {
  43404. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  43405. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  43406. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  43407. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  43408. var vignetteScaleX = vignetteScaleY * aspectRatio;
  43409. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  43410. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  43411. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  43412. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  43413. var vignettePower = -2.0 * this.vignetteWeight;
  43414. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  43415. }
  43416. // Exposure
  43417. effect.setFloat("exposureLinear", this.exposure);
  43418. // Contrast
  43419. effect.setFloat("contrast", this.contrast);
  43420. // Color transform settings
  43421. if (this.colorGradingTexture) {
  43422. effect.setTexture("txColorTransform", this.colorGradingTexture);
  43423. var textureSize = this.colorGradingTexture.getSize().height;
  43424. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  43425. 0.5 / textureSize, // textureOffset
  43426. textureSize, // textureSize
  43427. this.colorGradingTexture.level // weight
  43428. );
  43429. }
  43430. };
  43431. /**
  43432. * Clones the current image processing instance.
  43433. * @return The cloned image processing
  43434. */
  43435. ImageProcessingConfiguration.prototype.clone = function () {
  43436. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  43437. };
  43438. /**
  43439. * Serializes the current image processing instance to a json representation.
  43440. * @return a JSON representation
  43441. */
  43442. ImageProcessingConfiguration.prototype.serialize = function () {
  43443. return BABYLON.SerializationHelper.Serialize(this);
  43444. };
  43445. /**
  43446. * Parses the image processing from a json representation.
  43447. * @param source the JSON source to parse
  43448. * @return The parsed image processing
  43449. */
  43450. ImageProcessingConfiguration.Parse = function (source) {
  43451. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  43452. };
  43453. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  43454. /**
  43455. * Used to apply the vignette as a mix with the pixel color.
  43456. */
  43457. get: function () {
  43458. return this._VIGNETTEMODE_MULTIPLY;
  43459. },
  43460. enumerable: true,
  43461. configurable: true
  43462. });
  43463. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  43464. /**
  43465. * Used to apply the vignette as a replacement of the pixel color.
  43466. */
  43467. get: function () {
  43468. return this._VIGNETTEMODE_OPAQUE;
  43469. },
  43470. enumerable: true,
  43471. configurable: true
  43472. });
  43473. // Static constants associated to the image processing.
  43474. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  43475. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  43476. __decorate([
  43477. BABYLON.serializeAsColorCurves()
  43478. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  43479. __decorate([
  43480. BABYLON.serialize()
  43481. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  43482. __decorate([
  43483. BABYLON.serializeAsTexture()
  43484. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  43485. __decorate([
  43486. BABYLON.serialize()
  43487. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  43488. __decorate([
  43489. BABYLON.serialize()
  43490. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  43491. __decorate([
  43492. BABYLON.serialize()
  43493. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  43494. __decorate([
  43495. BABYLON.serialize()
  43496. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  43497. __decorate([
  43498. BABYLON.serialize()
  43499. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  43500. __decorate([
  43501. BABYLON.serialize()
  43502. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  43503. __decorate([
  43504. BABYLON.serialize()
  43505. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  43506. __decorate([
  43507. BABYLON.serialize()
  43508. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  43509. __decorate([
  43510. BABYLON.serialize()
  43511. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  43512. __decorate([
  43513. BABYLON.serialize()
  43514. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  43515. __decorate([
  43516. BABYLON.serializeAsColor4()
  43517. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  43518. __decorate([
  43519. BABYLON.serialize()
  43520. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  43521. __decorate([
  43522. BABYLON.serialize()
  43523. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  43524. __decorate([
  43525. BABYLON.serialize()
  43526. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  43527. __decorate([
  43528. BABYLON.serialize()
  43529. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  43530. return ImageProcessingConfiguration;
  43531. }());
  43532. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  43533. })(BABYLON || (BABYLON = {}));
  43534. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  43535. /// <reference path="babylon.mesh.ts" />
  43536. var BABYLON;
  43537. (function (BABYLON) {
  43538. var GroundMesh = (function (_super) {
  43539. __extends(GroundMesh, _super);
  43540. function GroundMesh(name, scene) {
  43541. var _this = _super.call(this, name, scene) || this;
  43542. _this.generateOctree = false;
  43543. _this._worldInverse = new BABYLON.Matrix();
  43544. return _this;
  43545. }
  43546. GroundMesh.prototype.getClassName = function () {
  43547. return "GroundMesh";
  43548. };
  43549. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  43550. get: function () {
  43551. return Math.min(this._subdivisionsX, this._subdivisionsY);
  43552. },
  43553. enumerable: true,
  43554. configurable: true
  43555. });
  43556. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  43557. get: function () {
  43558. return this._subdivisionsX;
  43559. },
  43560. enumerable: true,
  43561. configurable: true
  43562. });
  43563. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  43564. get: function () {
  43565. return this._subdivisionsY;
  43566. },
  43567. enumerable: true,
  43568. configurable: true
  43569. });
  43570. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  43571. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  43572. this._subdivisionsX = chunksCount;
  43573. this._subdivisionsY = chunksCount;
  43574. this.subdivide(chunksCount);
  43575. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  43576. };
  43577. /**
  43578. * Returns a height (y) value in the Worl system :
  43579. * the ground altitude at the coordinates (x, z) expressed in the World system.
  43580. * Returns the ground y position if (x, z) are outside the ground surface.
  43581. */
  43582. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  43583. var world = this.getWorldMatrix();
  43584. var invMat = BABYLON.Tmp.Matrix[5];
  43585. world.invertToRef(invMat);
  43586. var tmpVect = BABYLON.Tmp.Vector3[8];
  43587. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  43588. x = tmpVect.x;
  43589. z = tmpVect.z;
  43590. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43591. return this.position.y;
  43592. }
  43593. if (!this._heightQuads || this._heightQuads.length == 0) {
  43594. this._initHeightQuads();
  43595. this._computeHeightQuads();
  43596. }
  43597. var facet = this._getFacetAt(x, z);
  43598. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  43599. // return y in the World system
  43600. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  43601. return tmpVect.y;
  43602. };
  43603. /**
  43604. * Returns a normalized vector (Vector3) orthogonal to the ground
  43605. * at the ground coordinates (x, z) expressed in the World system.
  43606. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  43607. */
  43608. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  43609. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  43610. this.getNormalAtCoordinatesToRef(x, z, normal);
  43611. return normal;
  43612. };
  43613. /**
  43614. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  43615. * at the ground coordinates (x, z) expressed in the World system.
  43616. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  43617. * Returns the GroundMesh.
  43618. */
  43619. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  43620. var world = this.getWorldMatrix();
  43621. var tmpMat = BABYLON.Tmp.Matrix[5];
  43622. world.invertToRef(tmpMat);
  43623. var tmpVect = BABYLON.Tmp.Vector3[8];
  43624. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  43625. x = tmpVect.x;
  43626. z = tmpVect.z;
  43627. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43628. return this;
  43629. }
  43630. if (!this._heightQuads || this._heightQuads.length == 0) {
  43631. this._initHeightQuads();
  43632. this._computeHeightQuads();
  43633. }
  43634. var facet = this._getFacetAt(x, z);
  43635. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  43636. return this;
  43637. };
  43638. /**
  43639. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  43640. * if the ground has been updated.
  43641. * This can be used in the render loop.
  43642. * Returns the GroundMesh.
  43643. */
  43644. GroundMesh.prototype.updateCoordinateHeights = function () {
  43645. if (!this._heightQuads || this._heightQuads.length == 0) {
  43646. this._initHeightQuads();
  43647. }
  43648. this._computeHeightQuads();
  43649. return this;
  43650. };
  43651. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  43652. GroundMesh.prototype._getFacetAt = function (x, z) {
  43653. // retrieve col and row from x, z coordinates in the ground local system
  43654. var subdivisionsX = this._subdivisionsX;
  43655. var subdivisionsY = this._subdivisionsY;
  43656. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  43657. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  43658. var quad = this._heightQuads[row * this._subdivisionsX + col];
  43659. var facet;
  43660. if (z < quad.slope.x * x + quad.slope.y) {
  43661. facet = quad.facet1;
  43662. }
  43663. else {
  43664. facet = quad.facet2;
  43665. }
  43666. return facet;
  43667. };
  43668. // Creates and populates the heightMap array with "facet" elements :
  43669. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  43670. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43671. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43672. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43673. // Returns the GroundMesh.
  43674. GroundMesh.prototype._initHeightQuads = function () {
  43675. var subdivisionsX = this._subdivisionsX;
  43676. var subdivisionsY = this._subdivisionsY;
  43677. this._heightQuads = new Array();
  43678. for (var row = 0; row < subdivisionsY; row++) {
  43679. for (var col = 0; col < subdivisionsX; col++) {
  43680. 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) };
  43681. this._heightQuads[row * subdivisionsX + col] = quad;
  43682. }
  43683. }
  43684. return this;
  43685. };
  43686. // Compute each quad element values and update the the heightMap array :
  43687. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43688. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43689. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43690. // Returns the GroundMesh.
  43691. GroundMesh.prototype._computeHeightQuads = function () {
  43692. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43693. var v1 = BABYLON.Tmp.Vector3[3];
  43694. var v2 = BABYLON.Tmp.Vector3[2];
  43695. var v3 = BABYLON.Tmp.Vector3[1];
  43696. var v4 = BABYLON.Tmp.Vector3[0];
  43697. var v1v2 = BABYLON.Tmp.Vector3[4];
  43698. var v1v3 = BABYLON.Tmp.Vector3[5];
  43699. var v1v4 = BABYLON.Tmp.Vector3[6];
  43700. var norm1 = BABYLON.Tmp.Vector3[7];
  43701. var norm2 = BABYLON.Tmp.Vector3[8];
  43702. var i = 0;
  43703. var j = 0;
  43704. var k = 0;
  43705. var cd = 0; // 2D slope coefficient : z = cd * x + h
  43706. var h = 0;
  43707. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  43708. var d2 = 0;
  43709. var subdivisionsX = this._subdivisionsX;
  43710. var subdivisionsY = this._subdivisionsY;
  43711. for (var row = 0; row < subdivisionsY; row++) {
  43712. for (var col = 0; col < subdivisionsX; col++) {
  43713. i = col * 3;
  43714. j = row * (subdivisionsX + 1) * 3;
  43715. k = (row + 1) * (subdivisionsX + 1) * 3;
  43716. v1.x = positions[j + i];
  43717. v1.y = positions[j + i + 1];
  43718. v1.z = positions[j + i + 2];
  43719. v2.x = positions[j + i + 3];
  43720. v2.y = positions[j + i + 4];
  43721. v2.z = positions[j + i + 5];
  43722. v3.x = positions[k + i];
  43723. v3.y = positions[k + i + 1];
  43724. v3.z = positions[k + i + 2];
  43725. v4.x = positions[k + i + 3];
  43726. v4.y = positions[k + i + 4];
  43727. v4.z = positions[k + i + 5];
  43728. // 2D slope V1V4
  43729. cd = (v4.z - v1.z) / (v4.x - v1.x);
  43730. h = v1.z - cd * v1.x; // v1 belongs to the slope
  43731. // facet equations :
  43732. // we compute each facet normal vector
  43733. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  43734. // we compute the value d by applying the equation to v1 which belongs to the plane
  43735. // then we store the facet equation in a Vector4
  43736. v2.subtractToRef(v1, v1v2);
  43737. v3.subtractToRef(v1, v1v3);
  43738. v4.subtractToRef(v1, v1v4);
  43739. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  43740. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  43741. norm1.normalize();
  43742. norm2.normalize();
  43743. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  43744. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  43745. var quad = this._heightQuads[row * subdivisionsX + col];
  43746. quad.slope.copyFromFloats(cd, h);
  43747. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  43748. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  43749. }
  43750. }
  43751. return this;
  43752. };
  43753. GroundMesh.prototype.serialize = function (serializationObject) {
  43754. _super.prototype.serialize.call(this, serializationObject);
  43755. serializationObject.subdivisionsX = this._subdivisionsX;
  43756. serializationObject.subdivisionsY = this._subdivisionsY;
  43757. serializationObject.minX = this._minX;
  43758. serializationObject.maxX = this._maxX;
  43759. serializationObject.minZ = this._minZ;
  43760. serializationObject.maxZ = this._maxZ;
  43761. serializationObject.width = this._width;
  43762. serializationObject.height = this._height;
  43763. };
  43764. GroundMesh.Parse = function (parsedMesh, scene) {
  43765. var result = new GroundMesh(parsedMesh.name, scene);
  43766. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  43767. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  43768. result._minX = parsedMesh.minX;
  43769. result._maxX = parsedMesh.maxX;
  43770. result._minZ = parsedMesh.minZ;
  43771. result._maxZ = parsedMesh.maxZ;
  43772. result._width = parsedMesh.width;
  43773. result._height = parsedMesh.height;
  43774. return result;
  43775. };
  43776. return GroundMesh;
  43777. }(BABYLON.Mesh));
  43778. BABYLON.GroundMesh = GroundMesh;
  43779. })(BABYLON || (BABYLON = {}));
  43780. //# sourceMappingURL=babylon.groundMesh.js.map
  43781. var BABYLON;
  43782. (function (BABYLON) {
  43783. /**
  43784. * Creates an instance based on a source mesh.
  43785. */
  43786. var InstancedMesh = (function (_super) {
  43787. __extends(InstancedMesh, _super);
  43788. function InstancedMesh(name, source) {
  43789. var _this = _super.call(this, name, source.getScene()) || this;
  43790. source.instances.push(_this);
  43791. _this._sourceMesh = source;
  43792. _this.position.copyFrom(source.position);
  43793. _this.rotation.copyFrom(source.rotation);
  43794. _this.scaling.copyFrom(source.scaling);
  43795. if (source.rotationQuaternion) {
  43796. _this.rotationQuaternion = source.rotationQuaternion.clone();
  43797. }
  43798. _this.infiniteDistance = source.infiniteDistance;
  43799. _this.setPivotMatrix(source.getPivotMatrix());
  43800. _this.refreshBoundingInfo();
  43801. _this._syncSubMeshes();
  43802. return _this;
  43803. }
  43804. /**
  43805. * Returns the string "InstancedMesh".
  43806. */
  43807. InstancedMesh.prototype.getClassName = function () {
  43808. return "InstancedMesh";
  43809. };
  43810. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  43811. // Methods
  43812. get: function () {
  43813. return this._sourceMesh.receiveShadows;
  43814. },
  43815. enumerable: true,
  43816. configurable: true
  43817. });
  43818. Object.defineProperty(InstancedMesh.prototype, "material", {
  43819. get: function () {
  43820. return this._sourceMesh.material;
  43821. },
  43822. enumerable: true,
  43823. configurable: true
  43824. });
  43825. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  43826. get: function () {
  43827. return this._sourceMesh.visibility;
  43828. },
  43829. enumerable: true,
  43830. configurable: true
  43831. });
  43832. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  43833. get: function () {
  43834. return this._sourceMesh.skeleton;
  43835. },
  43836. enumerable: true,
  43837. configurable: true
  43838. });
  43839. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  43840. get: function () {
  43841. return this._sourceMesh.renderingGroupId;
  43842. },
  43843. enumerable: true,
  43844. configurable: true
  43845. });
  43846. /**
  43847. * Returns the total number of vertices (integer).
  43848. */
  43849. InstancedMesh.prototype.getTotalVertices = function () {
  43850. return this._sourceMesh.getTotalVertices();
  43851. };
  43852. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  43853. get: function () {
  43854. return this._sourceMesh;
  43855. },
  43856. enumerable: true,
  43857. configurable: true
  43858. });
  43859. /**
  43860. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  43861. */
  43862. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  43863. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  43864. };
  43865. /**
  43866. * Sets the vertex data of the mesh geometry for the requested `kind`.
  43867. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  43868. * The `data` are either a numeric array either a Float32Array.
  43869. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  43870. * 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).
  43871. * Note that a new underlying VertexBuffer object is created each call.
  43872. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  43873. *
  43874. * Possible `kind` values :
  43875. * - BABYLON.VertexBuffer.PositionKind
  43876. * - BABYLON.VertexBuffer.UVKind
  43877. * - BABYLON.VertexBuffer.UV2Kind
  43878. * - BABYLON.VertexBuffer.UV3Kind
  43879. * - BABYLON.VertexBuffer.UV4Kind
  43880. * - BABYLON.VertexBuffer.UV5Kind
  43881. * - BABYLON.VertexBuffer.UV6Kind
  43882. * - BABYLON.VertexBuffer.ColorKind
  43883. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43884. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43885. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43886. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43887. *
  43888. * Returns the Mesh.
  43889. */
  43890. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  43891. if (this.sourceMesh) {
  43892. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  43893. }
  43894. return this.sourceMesh;
  43895. };
  43896. /**
  43897. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  43898. * If the mesh has no geometry, it is simply returned as it is.
  43899. * The `data` are either a numeric array either a Float32Array.
  43900. * No new underlying VertexBuffer object is created.
  43901. * 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.
  43902. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  43903. *
  43904. * Possible `kind` values :
  43905. * - BABYLON.VertexBuffer.PositionKind
  43906. * - BABYLON.VertexBuffer.UVKind
  43907. * - BABYLON.VertexBuffer.UV2Kind
  43908. * - BABYLON.VertexBuffer.UV3Kind
  43909. * - BABYLON.VertexBuffer.UV4Kind
  43910. * - BABYLON.VertexBuffer.UV5Kind
  43911. * - BABYLON.VertexBuffer.UV6Kind
  43912. * - BABYLON.VertexBuffer.ColorKind
  43913. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43914. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43915. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43916. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43917. *
  43918. * Returns the Mesh.
  43919. */
  43920. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  43921. if (this.sourceMesh) {
  43922. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  43923. }
  43924. return this.sourceMesh;
  43925. };
  43926. /**
  43927. * Sets the mesh indices.
  43928. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  43929. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  43930. * This method creates a new index buffer each call.
  43931. * Returns the Mesh.
  43932. */
  43933. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  43934. if (this.sourceMesh) {
  43935. this.sourceMesh.setIndices(indices, totalVertices);
  43936. }
  43937. return this.sourceMesh;
  43938. };
  43939. /**
  43940. * Boolean : True if the mesh owns the requested kind of data.
  43941. */
  43942. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  43943. return this._sourceMesh.isVerticesDataPresent(kind);
  43944. };
  43945. /**
  43946. * Returns an array of indices (IndicesArray).
  43947. */
  43948. InstancedMesh.prototype.getIndices = function () {
  43949. return this._sourceMesh.getIndices();
  43950. };
  43951. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  43952. get: function () {
  43953. return this._sourceMesh._positions;
  43954. },
  43955. enumerable: true,
  43956. configurable: true
  43957. });
  43958. /**
  43959. * Sets a new updated BoundingInfo to the mesh.
  43960. * Returns the mesh.
  43961. */
  43962. InstancedMesh.prototype.refreshBoundingInfo = function () {
  43963. var meshBB = this._sourceMesh.getBoundingInfo();
  43964. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  43965. this._updateBoundingInfo();
  43966. return this;
  43967. };
  43968. InstancedMesh.prototype._preActivate = function () {
  43969. if (this._currentLOD) {
  43970. this._currentLOD._preActivate();
  43971. }
  43972. return this;
  43973. };
  43974. InstancedMesh.prototype._activate = function (renderId) {
  43975. if (this._currentLOD) {
  43976. this._currentLOD._registerInstanceForRenderId(this, renderId);
  43977. }
  43978. return this;
  43979. };
  43980. /**
  43981. * Returns the current associated LOD AbstractMesh.
  43982. */
  43983. InstancedMesh.prototype.getLOD = function (camera) {
  43984. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  43985. if (this._currentLOD === this.sourceMesh) {
  43986. return this;
  43987. }
  43988. return this._currentLOD;
  43989. };
  43990. InstancedMesh.prototype._syncSubMeshes = function () {
  43991. this.releaseSubMeshes();
  43992. if (this._sourceMesh.subMeshes) {
  43993. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  43994. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  43995. }
  43996. }
  43997. return this;
  43998. };
  43999. InstancedMesh.prototype._generatePointsArray = function () {
  44000. return this._sourceMesh._generatePointsArray();
  44001. };
  44002. /**
  44003. * Creates a new InstancedMesh from the current mesh.
  44004. * - name (string) : the cloned mesh name
  44005. * - newParent (optional Node) : the optional Node to parent the clone to.
  44006. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  44007. *
  44008. * Returns the clone.
  44009. */
  44010. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  44011. var result = this._sourceMesh.createInstance(name);
  44012. // Deep copy
  44013. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  44014. // Bounding info
  44015. this.refreshBoundingInfo();
  44016. // Parent
  44017. if (newParent) {
  44018. result.parent = newParent;
  44019. }
  44020. if (!doNotCloneChildren) {
  44021. // Children
  44022. for (var index = 0; index < this.getScene().meshes.length; index++) {
  44023. var mesh = this.getScene().meshes[index];
  44024. if (mesh.parent === this) {
  44025. mesh.clone(mesh.name, result);
  44026. }
  44027. }
  44028. }
  44029. result.computeWorldMatrix(true);
  44030. return result;
  44031. };
  44032. /**
  44033. * Disposes the InstancedMesh.
  44034. * Returns nothing.
  44035. */
  44036. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  44037. // Remove from mesh
  44038. var index = this._sourceMesh.instances.indexOf(this);
  44039. this._sourceMesh.instances.splice(index, 1);
  44040. _super.prototype.dispose.call(this, doNotRecurse);
  44041. };
  44042. return InstancedMesh;
  44043. }(BABYLON.AbstractMesh));
  44044. BABYLON.InstancedMesh = InstancedMesh;
  44045. })(BABYLON || (BABYLON = {}));
  44046. //# sourceMappingURL=babylon.instancedMesh.js.map
  44047. /// <reference path="babylon.mesh.ts" />
  44048. var BABYLON;
  44049. (function (BABYLON) {
  44050. var LinesMesh = (function (_super) {
  44051. __extends(LinesMesh, _super);
  44052. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  44053. if (parent === void 0) { parent = null; }
  44054. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  44055. _this.useVertexColor = useVertexColor;
  44056. _this.color = new BABYLON.Color3(1, 1, 1);
  44057. _this.alpha = 1;
  44058. if (source) {
  44059. _this.color = source.color.clone();
  44060. _this.alpha = source.alpha;
  44061. _this.useVertexColor = source.useVertexColor;
  44062. }
  44063. _this._intersectionThreshold = 0.1;
  44064. var options = {
  44065. attributes: [BABYLON.VertexBuffer.PositionKind],
  44066. uniforms: ["world", "viewProjection"],
  44067. needAlphaBlending: false,
  44068. };
  44069. if (!useVertexColor) {
  44070. options.uniforms.push("color");
  44071. options.needAlphaBlending = true;
  44072. }
  44073. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  44074. return _this;
  44075. }
  44076. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  44077. /**
  44078. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  44079. * This margin is expressed in world space coordinates, so its value may vary.
  44080. * Default value is 0.1
  44081. * @returns the intersection Threshold value.
  44082. */
  44083. get: function () {
  44084. return this._intersectionThreshold;
  44085. },
  44086. /**
  44087. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  44088. * This margin is expressed in world space coordinates, so its value may vary.
  44089. * @param value the new threshold to apply
  44090. */
  44091. set: function (value) {
  44092. if (this._intersectionThreshold === value) {
  44093. return;
  44094. }
  44095. this._intersectionThreshold = value;
  44096. if (this.geometry) {
  44097. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  44098. }
  44099. },
  44100. enumerable: true,
  44101. configurable: true
  44102. });
  44103. /**
  44104. * Returns the string "LineMesh"
  44105. */
  44106. LinesMesh.prototype.getClassName = function () {
  44107. return "LinesMesh";
  44108. };
  44109. Object.defineProperty(LinesMesh.prototype, "material", {
  44110. get: function () {
  44111. return this._colorShader;
  44112. },
  44113. enumerable: true,
  44114. configurable: true
  44115. });
  44116. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  44117. get: function () {
  44118. return false;
  44119. },
  44120. enumerable: true,
  44121. configurable: true
  44122. });
  44123. LinesMesh.prototype.createInstance = function (name) {
  44124. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  44125. return null;
  44126. };
  44127. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  44128. // VBOs
  44129. this._geometry._bind(this._colorShader.getEffect());
  44130. // Color
  44131. if (!this.useVertexColor) {
  44132. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  44133. }
  44134. return this;
  44135. };
  44136. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  44137. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  44138. return this;
  44139. }
  44140. var engine = this.getScene().getEngine();
  44141. // Draw order
  44142. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  44143. return this;
  44144. };
  44145. LinesMesh.prototype.dispose = function (doNotRecurse) {
  44146. this._colorShader.dispose();
  44147. _super.prototype.dispose.call(this, doNotRecurse);
  44148. };
  44149. /**
  44150. * Returns a new LineMesh object cloned from the current one.
  44151. */
  44152. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  44153. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  44154. };
  44155. return LinesMesh;
  44156. }(BABYLON.Mesh));
  44157. BABYLON.LinesMesh = LinesMesh;
  44158. })(BABYLON || (BABYLON = {}));
  44159. //# sourceMappingURL=babylon.linesMesh.js.map
  44160. var BABYLON;
  44161. (function (BABYLON) {
  44162. var StandardMaterialDefines = (function (_super) {
  44163. __extends(StandardMaterialDefines, _super);
  44164. function StandardMaterialDefines() {
  44165. var _this = _super.call(this) || this;
  44166. _this.MAINUV1 = false;
  44167. _this.MAINUV2 = false;
  44168. _this.DIFFUSE = false;
  44169. _this.DIFFUSEDIRECTUV = 0;
  44170. _this.AMBIENT = false;
  44171. _this.AMBIENTDIRECTUV = 0;
  44172. _this.OPACITY = false;
  44173. _this.OPACITYDIRECTUV = 0;
  44174. _this.OPACITYRGB = false;
  44175. _this.REFLECTION = false;
  44176. _this.EMISSIVE = false;
  44177. _this.EMISSIVEDIRECTUV = 0;
  44178. _this.SPECULAR = false;
  44179. _this.SPECULARDIRECTUV = 0;
  44180. _this.BUMP = false;
  44181. _this.BUMPDIRECTUV = 0;
  44182. _this.PARALLAX = false;
  44183. _this.PARALLAXOCCLUSION = false;
  44184. _this.SPECULAROVERALPHA = false;
  44185. _this.CLIPPLANE = false;
  44186. _this.ALPHATEST = false;
  44187. _this.ALPHAFROMDIFFUSE = false;
  44188. _this.POINTSIZE = false;
  44189. _this.FOG = false;
  44190. _this.SPECULARTERM = false;
  44191. _this.DIFFUSEFRESNEL = false;
  44192. _this.OPACITYFRESNEL = false;
  44193. _this.REFLECTIONFRESNEL = false;
  44194. _this.REFRACTIONFRESNEL = false;
  44195. _this.EMISSIVEFRESNEL = false;
  44196. _this.FRESNEL = false;
  44197. _this.NORMAL = false;
  44198. _this.UV1 = false;
  44199. _this.UV2 = false;
  44200. _this.VERTEXCOLOR = false;
  44201. _this.VERTEXALPHA = false;
  44202. _this.NUM_BONE_INFLUENCERS = 0;
  44203. _this.BonesPerMesh = 0;
  44204. _this.INSTANCES = false;
  44205. _this.GLOSSINESS = false;
  44206. _this.ROUGHNESS = false;
  44207. _this.EMISSIVEASILLUMINATION = false;
  44208. _this.LINKEMISSIVEWITHDIFFUSE = false;
  44209. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  44210. _this.LIGHTMAP = false;
  44211. _this.LIGHTMAPDIRECTUV = 0;
  44212. _this.USELIGHTMAPASSHADOWMAP = false;
  44213. _this.REFLECTIONMAP_3D = false;
  44214. _this.REFLECTIONMAP_SPHERICAL = false;
  44215. _this.REFLECTIONMAP_PLANAR = false;
  44216. _this.REFLECTIONMAP_CUBIC = false;
  44217. _this.REFLECTIONMAP_PROJECTION = false;
  44218. _this.REFLECTIONMAP_SKYBOX = false;
  44219. _this.REFLECTIONMAP_EXPLICIT = false;
  44220. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44221. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44222. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44223. _this.INVERTCUBICMAP = false;
  44224. _this.LOGARITHMICDEPTH = false;
  44225. _this.REFRACTION = false;
  44226. _this.REFRACTIONMAP_3D = false;
  44227. _this.REFLECTIONOVERALPHA = false;
  44228. _this.TWOSIDEDLIGHTING = false;
  44229. _this.SHADOWFLOAT = false;
  44230. _this.MORPHTARGETS = false;
  44231. _this.MORPHTARGETS_NORMAL = false;
  44232. _this.MORPHTARGETS_TANGENT = false;
  44233. _this.NUM_MORPH_INFLUENCERS = 0;
  44234. _this.USERIGHTHANDEDSYSTEM = false;
  44235. _this.IMAGEPROCESSING = false;
  44236. _this.VIGNETTE = false;
  44237. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44238. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44239. _this.TONEMAPPING = false;
  44240. _this.CONTRAST = false;
  44241. _this.COLORCURVES = false;
  44242. _this.COLORGRADING = false;
  44243. _this.SAMPLER3DGREENDEPTH = false;
  44244. _this.SAMPLER3DBGRMAP = false;
  44245. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44246. _this.EXPOSURE = false;
  44247. _this.rebuild();
  44248. return _this;
  44249. }
  44250. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  44251. var modes = [
  44252. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  44253. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  44254. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  44255. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  44256. ];
  44257. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  44258. var mode = modes_1[_i];
  44259. this[mode] = (mode === modeToEnable);
  44260. }
  44261. };
  44262. return StandardMaterialDefines;
  44263. }(BABYLON.MaterialDefines));
  44264. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  44265. var StandardMaterial = (function (_super) {
  44266. __extends(StandardMaterial, _super);
  44267. function StandardMaterial(name, scene) {
  44268. var _this = _super.call(this, name, scene) || this;
  44269. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44270. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  44271. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  44272. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44273. _this.specularPower = 64;
  44274. _this._useAlphaFromDiffuseTexture = false;
  44275. _this._useEmissiveAsIllumination = false;
  44276. _this._linkEmissiveWithDiffuse = false;
  44277. _this._useSpecularOverAlpha = false;
  44278. _this._useReflectionOverAlpha = false;
  44279. _this._disableLighting = false;
  44280. _this._useParallax = false;
  44281. _this._useParallaxOcclusion = false;
  44282. _this.parallaxScaleBias = 0.05;
  44283. _this._roughness = 0;
  44284. _this.indexOfRefraction = 0.98;
  44285. _this.invertRefractionY = true;
  44286. _this._useLightmapAsShadowmap = false;
  44287. _this._useReflectionFresnelFromSpecular = false;
  44288. _this._useGlossinessFromSpecularMapAlpha = false;
  44289. _this._maxSimultaneousLights = 4;
  44290. /**
  44291. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44292. */
  44293. _this._invertNormalMapX = false;
  44294. /**
  44295. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44296. */
  44297. _this._invertNormalMapY = false;
  44298. /**
  44299. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44300. */
  44301. _this._twoSidedLighting = false;
  44302. _this._renderTargets = new BABYLON.SmartArray(16);
  44303. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  44304. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44305. // Setup the default processing configuration to the scene.
  44306. _this._attachImageProcessingConfiguration(null);
  44307. _this.getRenderTargetTextures = function () {
  44308. _this._renderTargets.reset();
  44309. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44310. _this._renderTargets.push(_this._reflectionTexture);
  44311. }
  44312. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44313. _this._renderTargets.push(_this._refractionTexture);
  44314. }
  44315. return _this._renderTargets;
  44316. };
  44317. return _this;
  44318. }
  44319. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  44320. /**
  44321. * Gets the image processing configuration used either in this material.
  44322. */
  44323. get: function () {
  44324. return this._imageProcessingConfiguration;
  44325. },
  44326. /**
  44327. * Sets the Default image processing configuration used either in the this material.
  44328. *
  44329. * If sets to null, the scene one is in use.
  44330. */
  44331. set: function (value) {
  44332. this._attachImageProcessingConfiguration(value);
  44333. // Ensure the effect will be rebuilt.
  44334. this._markAllSubMeshesAsTexturesDirty();
  44335. },
  44336. enumerable: true,
  44337. configurable: true
  44338. });
  44339. /**
  44340. * Attaches a new image processing configuration to the Standard Material.
  44341. * @param configuration
  44342. */
  44343. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44344. var _this = this;
  44345. if (configuration === this._imageProcessingConfiguration) {
  44346. return;
  44347. }
  44348. // Detaches observer.
  44349. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44350. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44351. }
  44352. // Pick the scene configuration if needed.
  44353. if (!configuration) {
  44354. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44355. }
  44356. else {
  44357. this._imageProcessingConfiguration = configuration;
  44358. }
  44359. // Attaches observer.
  44360. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44361. _this._markAllSubMeshesAsImageProcessingDirty();
  44362. });
  44363. };
  44364. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  44365. /**
  44366. * Gets wether the color curves effect is enabled.
  44367. */
  44368. get: function () {
  44369. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44370. },
  44371. /**
  44372. * Sets wether the color curves effect is enabled.
  44373. */
  44374. set: function (value) {
  44375. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44376. },
  44377. enumerable: true,
  44378. configurable: true
  44379. });
  44380. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  44381. /**
  44382. * Gets wether the color grading effect is enabled.
  44383. */
  44384. get: function () {
  44385. return this.imageProcessingConfiguration.colorGradingEnabled;
  44386. },
  44387. /**
  44388. * Gets wether the color grading effect is enabled.
  44389. */
  44390. set: function (value) {
  44391. this.imageProcessingConfiguration.colorGradingEnabled = value;
  44392. },
  44393. enumerable: true,
  44394. configurable: true
  44395. });
  44396. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  44397. /**
  44398. * Gets wether tonemapping is enabled or not.
  44399. */
  44400. get: function () {
  44401. return this._imageProcessingConfiguration.toneMappingEnabled;
  44402. },
  44403. /**
  44404. * Sets wether tonemapping is enabled or not
  44405. */
  44406. set: function (value) {
  44407. this._imageProcessingConfiguration.toneMappingEnabled = value;
  44408. },
  44409. enumerable: true,
  44410. configurable: true
  44411. });
  44412. ;
  44413. ;
  44414. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  44415. /**
  44416. * The camera exposure used on this material.
  44417. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44418. * This corresponds to a photographic exposure.
  44419. */
  44420. get: function () {
  44421. return this._imageProcessingConfiguration.exposure;
  44422. },
  44423. /**
  44424. * The camera exposure used on this material.
  44425. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44426. * This corresponds to a photographic exposure.
  44427. */
  44428. set: function (value) {
  44429. this._imageProcessingConfiguration.exposure = value;
  44430. },
  44431. enumerable: true,
  44432. configurable: true
  44433. });
  44434. ;
  44435. ;
  44436. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  44437. /**
  44438. * Gets The camera contrast used on this material.
  44439. */
  44440. get: function () {
  44441. return this._imageProcessingConfiguration.contrast;
  44442. },
  44443. /**
  44444. * Sets The camera contrast used on this material.
  44445. */
  44446. set: function (value) {
  44447. this._imageProcessingConfiguration.contrast = value;
  44448. },
  44449. enumerable: true,
  44450. configurable: true
  44451. });
  44452. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  44453. /**
  44454. * Gets the Color Grading 2D Lookup Texture.
  44455. */
  44456. get: function () {
  44457. return this._imageProcessingConfiguration.colorGradingTexture;
  44458. },
  44459. /**
  44460. * Sets the Color Grading 2D Lookup Texture.
  44461. */
  44462. set: function (value) {
  44463. this._imageProcessingConfiguration.colorGradingTexture = value;
  44464. },
  44465. enumerable: true,
  44466. configurable: true
  44467. });
  44468. StandardMaterial.prototype.getClassName = function () {
  44469. return "StandardMaterial";
  44470. };
  44471. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  44472. get: function () {
  44473. return this._useLogarithmicDepth;
  44474. },
  44475. set: function (value) {
  44476. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44477. this._markAllSubMeshesAsMiscDirty();
  44478. },
  44479. enumerable: true,
  44480. configurable: true
  44481. });
  44482. StandardMaterial.prototype.needAlphaBlending = function () {
  44483. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  44484. };
  44485. StandardMaterial.prototype.needAlphaTesting = function () {
  44486. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  44487. };
  44488. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  44489. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  44490. };
  44491. StandardMaterial.prototype.getAlphaTestTexture = function () {
  44492. return this._diffuseTexture;
  44493. };
  44494. /**
  44495. * Child classes can use it to update shaders
  44496. */
  44497. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44498. if (this.isFrozen) {
  44499. if (this._wasPreviouslyReady && subMesh.effect) {
  44500. return true;
  44501. }
  44502. }
  44503. if (!subMesh._materialDefines) {
  44504. subMesh._materialDefines = new StandardMaterialDefines();
  44505. }
  44506. var scene = this.getScene();
  44507. var defines = subMesh._materialDefines;
  44508. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44509. if (defines._renderId === scene.getRenderId()) {
  44510. return true;
  44511. }
  44512. }
  44513. var engine = scene.getEngine();
  44514. // Lights
  44515. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44516. // Textures
  44517. if (defines._areTexturesDirty) {
  44518. defines._needUVs = false;
  44519. defines.MAINUV1 = false;
  44520. defines.MAINUV2 = false;
  44521. if (scene.texturesEnabled) {
  44522. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44523. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  44524. return false;
  44525. }
  44526. else {
  44527. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  44528. }
  44529. }
  44530. else {
  44531. defines.DIFFUSE = false;
  44532. }
  44533. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44534. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44535. return false;
  44536. }
  44537. else {
  44538. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44539. }
  44540. }
  44541. else {
  44542. defines.AMBIENT = false;
  44543. }
  44544. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44545. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44546. return false;
  44547. }
  44548. else {
  44549. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44550. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44551. }
  44552. }
  44553. else {
  44554. defines.OPACITY = false;
  44555. }
  44556. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44557. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  44558. return false;
  44559. }
  44560. else {
  44561. defines._needNormals = true;
  44562. defines.REFLECTION = true;
  44563. defines.ROUGHNESS = (this._roughness > 0);
  44564. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  44565. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  44566. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  44567. switch (this._reflectionTexture.coordinatesMode) {
  44568. case BABYLON.Texture.CUBIC_MODE:
  44569. case BABYLON.Texture.INVCUBIC_MODE:
  44570. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  44571. break;
  44572. case BABYLON.Texture.EXPLICIT_MODE:
  44573. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  44574. break;
  44575. case BABYLON.Texture.PLANAR_MODE:
  44576. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  44577. break;
  44578. case BABYLON.Texture.PROJECTION_MODE:
  44579. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  44580. break;
  44581. case BABYLON.Texture.SKYBOX_MODE:
  44582. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  44583. break;
  44584. case BABYLON.Texture.SPHERICAL_MODE:
  44585. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  44586. break;
  44587. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44588. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  44589. break;
  44590. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44591. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  44592. break;
  44593. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44594. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  44595. break;
  44596. }
  44597. }
  44598. }
  44599. else {
  44600. defines.REFLECTION = false;
  44601. }
  44602. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44603. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44604. return false;
  44605. }
  44606. else {
  44607. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44608. }
  44609. }
  44610. else {
  44611. defines.EMISSIVE = false;
  44612. }
  44613. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44614. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44615. return false;
  44616. }
  44617. else {
  44618. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44619. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44620. }
  44621. }
  44622. else {
  44623. defines.LIGHTMAP = false;
  44624. }
  44625. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44626. if (!this._specularTexture.isReadyOrNotBlocking()) {
  44627. return false;
  44628. }
  44629. else {
  44630. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  44631. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  44632. }
  44633. }
  44634. else {
  44635. defines.SPECULAR = false;
  44636. }
  44637. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  44638. // Bump texure can not be not blocking.
  44639. if (!this._bumpTexture.isReady()) {
  44640. return false;
  44641. }
  44642. else {
  44643. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44644. defines.PARALLAX = this._useParallax;
  44645. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  44646. }
  44647. }
  44648. else {
  44649. defines.BUMP = false;
  44650. }
  44651. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44652. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  44653. return false;
  44654. }
  44655. else {
  44656. defines._needUVs = true;
  44657. defines.REFRACTION = true;
  44658. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  44659. }
  44660. }
  44661. else {
  44662. defines.REFRACTION = false;
  44663. }
  44664. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  44665. }
  44666. else {
  44667. defines.DIFFUSE = false;
  44668. defines.AMBIENT = false;
  44669. defines.OPACITY = false;
  44670. defines.REFLECTION = false;
  44671. defines.EMISSIVE = false;
  44672. defines.LIGHTMAP = false;
  44673. defines.BUMP = false;
  44674. defines.REFRACTION = false;
  44675. }
  44676. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  44677. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  44678. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  44679. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44680. }
  44681. if (defines._areImageProcessingDirty) {
  44682. if (!this._imageProcessingConfiguration.isReady()) {
  44683. return false;
  44684. }
  44685. this._imageProcessingConfiguration.prepareDefines(defines);
  44686. }
  44687. if (defines._areFresnelDirty) {
  44688. if (StandardMaterial.FresnelEnabled) {
  44689. // Fresnel
  44690. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  44691. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  44692. this._reflectionFresnelParameters) {
  44693. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  44694. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  44695. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  44696. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  44697. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  44698. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  44699. defines._needNormals = true;
  44700. defines.FRESNEL = true;
  44701. }
  44702. }
  44703. else {
  44704. defines.FRESNEL = false;
  44705. }
  44706. }
  44707. // Misc.
  44708. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  44709. // Attribs
  44710. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  44711. // Values that need to be evaluated on every frame
  44712. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  44713. // Get correct effect
  44714. if (defines.isDirty) {
  44715. defines.markAsProcessed();
  44716. scene.resetCachedMaterial();
  44717. // Fallbacks
  44718. var fallbacks = new BABYLON.EffectFallbacks();
  44719. if (defines.REFLECTION) {
  44720. fallbacks.addFallback(0, "REFLECTION");
  44721. }
  44722. if (defines.SPECULAR) {
  44723. fallbacks.addFallback(0, "SPECULAR");
  44724. }
  44725. if (defines.BUMP) {
  44726. fallbacks.addFallback(0, "BUMP");
  44727. }
  44728. if (defines.PARALLAX) {
  44729. fallbacks.addFallback(1, "PARALLAX");
  44730. }
  44731. if (defines.PARALLAXOCCLUSION) {
  44732. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44733. }
  44734. if (defines.SPECULAROVERALPHA) {
  44735. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44736. }
  44737. if (defines.FOG) {
  44738. fallbacks.addFallback(1, "FOG");
  44739. }
  44740. if (defines.POINTSIZE) {
  44741. fallbacks.addFallback(0, "POINTSIZE");
  44742. }
  44743. if (defines.LOGARITHMICDEPTH) {
  44744. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44745. }
  44746. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  44747. if (defines.SPECULARTERM) {
  44748. fallbacks.addFallback(0, "SPECULARTERM");
  44749. }
  44750. if (defines.DIFFUSEFRESNEL) {
  44751. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  44752. }
  44753. if (defines.OPACITYFRESNEL) {
  44754. fallbacks.addFallback(2, "OPACITYFRESNEL");
  44755. }
  44756. if (defines.REFLECTIONFRESNEL) {
  44757. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  44758. }
  44759. if (defines.EMISSIVEFRESNEL) {
  44760. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  44761. }
  44762. if (defines.FRESNEL) {
  44763. fallbacks.addFallback(4, "FRESNEL");
  44764. }
  44765. //Attributes
  44766. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44767. if (defines.NORMAL) {
  44768. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44769. }
  44770. if (defines.UV1) {
  44771. attribs.push(BABYLON.VertexBuffer.UVKind);
  44772. }
  44773. if (defines.UV2) {
  44774. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44775. }
  44776. if (defines.VERTEXCOLOR) {
  44777. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44778. }
  44779. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44780. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44781. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44782. var shaderName = "default";
  44783. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  44784. "vFogInfos", "vFogColor", "pointSize",
  44785. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44786. "mBones",
  44787. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44788. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  44789. "logarithmicDepthConstant", "vNormalReoderParams"
  44790. ];
  44791. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  44792. var uniformBuffers = ["Material", "Scene"];
  44793. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44794. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44795. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44796. uniformsNames: uniforms,
  44797. uniformBuffersNames: uniformBuffers,
  44798. samplers: samplers,
  44799. defines: defines,
  44800. maxSimultaneousLights: this._maxSimultaneousLights
  44801. });
  44802. if (this.customShaderNameResolve) {
  44803. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  44804. }
  44805. var join = defines.toString();
  44806. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  44807. attributes: attribs,
  44808. uniformsNames: uniforms,
  44809. uniformBuffersNames: uniformBuffers,
  44810. samplers: samplers,
  44811. defines: join,
  44812. fallbacks: fallbacks,
  44813. onCompiled: this.onCompiled,
  44814. onError: this.onError,
  44815. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44816. }, engine), defines);
  44817. this.buildUniformLayout();
  44818. }
  44819. if (!subMesh.effect.isReady()) {
  44820. return false;
  44821. }
  44822. defines._renderId = scene.getRenderId();
  44823. this._wasPreviouslyReady = true;
  44824. return true;
  44825. };
  44826. StandardMaterial.prototype.buildUniformLayout = function () {
  44827. // Order is important !
  44828. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  44829. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  44830. this._uniformBuffer.addUniform("opacityParts", 4);
  44831. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  44832. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  44833. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  44834. this._uniformBuffer.addUniform("refractionRightColor", 4);
  44835. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  44836. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  44837. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  44838. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  44839. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44840. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44841. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44842. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44843. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  44844. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44845. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  44846. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44847. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44848. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44849. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44850. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44851. this._uniformBuffer.addUniform("specularMatrix", 16);
  44852. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44853. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  44854. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44855. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44856. this._uniformBuffer.addUniform("vSpecularColor", 4);
  44857. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44858. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  44859. this._uniformBuffer.addUniform("pointSize", 1);
  44860. this._uniformBuffer.create();
  44861. };
  44862. StandardMaterial.prototype.unbind = function () {
  44863. if (this._activeEffect) {
  44864. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44865. this._activeEffect.setTexture("reflection2DSampler", null);
  44866. }
  44867. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44868. this._activeEffect.setTexture("refraction2DSampler", null);
  44869. }
  44870. }
  44871. _super.prototype.unbind.call(this);
  44872. };
  44873. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44874. var scene = this.getScene();
  44875. var defines = subMesh._materialDefines;
  44876. if (!defines) {
  44877. return;
  44878. }
  44879. var effect = subMesh.effect;
  44880. this._activeEffect = effect;
  44881. // Matrices
  44882. this.bindOnlyWorldMatrix(world);
  44883. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44884. // Bones
  44885. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  44886. if (mustRebind) {
  44887. this._uniformBuffer.bindToEffect(effect, "Material");
  44888. this.bindViewProjection(effect);
  44889. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44890. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  44891. // Fresnel
  44892. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  44893. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  44894. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  44895. }
  44896. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44897. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44898. }
  44899. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  44900. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  44901. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  44902. }
  44903. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  44904. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  44905. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  44906. }
  44907. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44908. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44909. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44910. }
  44911. }
  44912. // Textures
  44913. if (scene.texturesEnabled) {
  44914. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44915. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  44916. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44917. }
  44918. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44919. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44920. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44921. }
  44922. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44923. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44924. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44925. }
  44926. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44927. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44928. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44929. }
  44930. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44931. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44932. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44933. }
  44934. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44935. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44936. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44937. }
  44938. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44939. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44940. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44941. }
  44942. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44943. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44944. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44945. if (scene._mirroredCameraPosition) {
  44946. 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);
  44947. }
  44948. else {
  44949. 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);
  44950. }
  44951. }
  44952. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44953. var depth = 1.0;
  44954. if (!this._refractionTexture.isCube) {
  44955. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44956. if (this._refractionTexture.depth) {
  44957. depth = this._refractionTexture.depth;
  44958. }
  44959. }
  44960. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44961. }
  44962. }
  44963. // Point size
  44964. if (this.pointsCloud) {
  44965. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44966. }
  44967. if (defines.SPECULARTERM) {
  44968. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44969. }
  44970. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44971. // Diffuse
  44972. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44973. }
  44974. // Textures
  44975. if (scene.texturesEnabled) {
  44976. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44977. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44978. }
  44979. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44980. effect.setTexture("ambientSampler", this._ambientTexture);
  44981. }
  44982. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44983. effect.setTexture("opacitySampler", this._opacityTexture);
  44984. }
  44985. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44986. if (this._reflectionTexture.isCube) {
  44987. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44988. }
  44989. else {
  44990. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44991. }
  44992. }
  44993. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44994. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44995. }
  44996. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44997. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44998. }
  44999. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  45000. effect.setTexture("specularSampler", this._specularTexture);
  45001. }
  45002. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  45003. effect.setTexture("bumpSampler", this._bumpTexture);
  45004. }
  45005. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  45006. var depth = 1.0;
  45007. if (this._refractionTexture.isCube) {
  45008. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  45009. }
  45010. else {
  45011. effect.setTexture("refraction2DSampler", this._refractionTexture);
  45012. }
  45013. }
  45014. }
  45015. // Clip plane
  45016. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  45017. // Colors
  45018. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  45019. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45020. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45021. }
  45022. if (mustRebind || !this.isFrozen) {
  45023. // Lights
  45024. if (scene.lightsEnabled && !this._disableLighting) {
  45025. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  45026. }
  45027. // View
  45028. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  45029. this.bindView(effect);
  45030. }
  45031. // Fog
  45032. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  45033. // Morph targets
  45034. if (defines.NUM_MORPH_INFLUENCERS) {
  45035. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  45036. }
  45037. // Log. depth
  45038. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  45039. // image processing
  45040. this._imageProcessingConfiguration.bind(this._activeEffect);
  45041. }
  45042. this._uniformBuffer.update();
  45043. this._afterBind(mesh, this._activeEffect);
  45044. };
  45045. StandardMaterial.prototype.getAnimatables = function () {
  45046. var results = [];
  45047. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  45048. results.push(this._diffuseTexture);
  45049. }
  45050. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45051. results.push(this._ambientTexture);
  45052. }
  45053. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45054. results.push(this._opacityTexture);
  45055. }
  45056. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45057. results.push(this._reflectionTexture);
  45058. }
  45059. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45060. results.push(this._emissiveTexture);
  45061. }
  45062. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  45063. results.push(this._specularTexture);
  45064. }
  45065. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45066. results.push(this._bumpTexture);
  45067. }
  45068. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45069. results.push(this._lightmapTexture);
  45070. }
  45071. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45072. results.push(this._refractionTexture);
  45073. }
  45074. return results;
  45075. };
  45076. StandardMaterial.prototype.getActiveTextures = function () {
  45077. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45078. if (this._diffuseTexture) {
  45079. activeTextures.push(this._diffuseTexture);
  45080. }
  45081. if (this._ambientTexture) {
  45082. activeTextures.push(this._ambientTexture);
  45083. }
  45084. if (this._opacityTexture) {
  45085. activeTextures.push(this._opacityTexture);
  45086. }
  45087. if (this._reflectionTexture) {
  45088. activeTextures.push(this._reflectionTexture);
  45089. }
  45090. if (this._emissiveTexture) {
  45091. activeTextures.push(this._emissiveTexture);
  45092. }
  45093. if (this._specularTexture) {
  45094. activeTextures.push(this._specularTexture);
  45095. }
  45096. if (this._bumpTexture) {
  45097. activeTextures.push(this._bumpTexture);
  45098. }
  45099. if (this._lightmapTexture) {
  45100. activeTextures.push(this._lightmapTexture);
  45101. }
  45102. if (this._refractionTexture) {
  45103. activeTextures.push(this._refractionTexture);
  45104. }
  45105. return activeTextures;
  45106. };
  45107. StandardMaterial.prototype.hasTexture = function (texture) {
  45108. if (_super.prototype.hasTexture.call(this, texture)) {
  45109. return true;
  45110. }
  45111. if (this._diffuseTexture === texture) {
  45112. return true;
  45113. }
  45114. if (this._ambientTexture === texture) {
  45115. return true;
  45116. }
  45117. if (this._opacityTexture === texture) {
  45118. return true;
  45119. }
  45120. if (this._reflectionTexture === texture) {
  45121. return true;
  45122. }
  45123. if (this._emissiveTexture === texture) {
  45124. return true;
  45125. }
  45126. if (this._specularTexture === texture) {
  45127. return true;
  45128. }
  45129. if (this._bumpTexture === texture) {
  45130. return true;
  45131. }
  45132. if (this._lightmapTexture === texture) {
  45133. return true;
  45134. }
  45135. if (this._refractionTexture === texture) {
  45136. return true;
  45137. }
  45138. return false;
  45139. };
  45140. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45141. if (forceDisposeTextures) {
  45142. if (this._diffuseTexture) {
  45143. this._diffuseTexture.dispose();
  45144. }
  45145. if (this._ambientTexture) {
  45146. this._ambientTexture.dispose();
  45147. }
  45148. if (this._opacityTexture) {
  45149. this._opacityTexture.dispose();
  45150. }
  45151. if (this._reflectionTexture) {
  45152. this._reflectionTexture.dispose();
  45153. }
  45154. if (this._emissiveTexture) {
  45155. this._emissiveTexture.dispose();
  45156. }
  45157. if (this._specularTexture) {
  45158. this._specularTexture.dispose();
  45159. }
  45160. if (this._bumpTexture) {
  45161. this._bumpTexture.dispose();
  45162. }
  45163. if (this._lightmapTexture) {
  45164. this._lightmapTexture.dispose();
  45165. }
  45166. if (this._refractionTexture) {
  45167. this._refractionTexture.dispose();
  45168. }
  45169. }
  45170. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45171. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45172. }
  45173. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45174. };
  45175. StandardMaterial.prototype.clone = function (name) {
  45176. var _this = this;
  45177. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  45178. result.name = name;
  45179. result.id = name;
  45180. return result;
  45181. };
  45182. StandardMaterial.prototype.serialize = function () {
  45183. return BABYLON.SerializationHelper.Serialize(this);
  45184. };
  45185. // Statics
  45186. StandardMaterial.Parse = function (source, scene, rootUrl) {
  45187. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  45188. };
  45189. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  45190. get: function () {
  45191. return StandardMaterial._DiffuseTextureEnabled;
  45192. },
  45193. set: function (value) {
  45194. if (StandardMaterial._DiffuseTextureEnabled === value) {
  45195. return;
  45196. }
  45197. StandardMaterial._DiffuseTextureEnabled = value;
  45198. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45199. },
  45200. enumerable: true,
  45201. configurable: true
  45202. });
  45203. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  45204. get: function () {
  45205. return StandardMaterial._AmbientTextureEnabled;
  45206. },
  45207. set: function (value) {
  45208. if (StandardMaterial._AmbientTextureEnabled === value) {
  45209. return;
  45210. }
  45211. StandardMaterial._AmbientTextureEnabled = value;
  45212. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45213. },
  45214. enumerable: true,
  45215. configurable: true
  45216. });
  45217. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  45218. get: function () {
  45219. return StandardMaterial._OpacityTextureEnabled;
  45220. },
  45221. set: function (value) {
  45222. if (StandardMaterial._OpacityTextureEnabled === value) {
  45223. return;
  45224. }
  45225. StandardMaterial._OpacityTextureEnabled = value;
  45226. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45227. },
  45228. enumerable: true,
  45229. configurable: true
  45230. });
  45231. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  45232. get: function () {
  45233. return StandardMaterial._ReflectionTextureEnabled;
  45234. },
  45235. set: function (value) {
  45236. if (StandardMaterial._ReflectionTextureEnabled === value) {
  45237. return;
  45238. }
  45239. StandardMaterial._ReflectionTextureEnabled = value;
  45240. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45241. },
  45242. enumerable: true,
  45243. configurable: true
  45244. });
  45245. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  45246. get: function () {
  45247. return StandardMaterial._EmissiveTextureEnabled;
  45248. },
  45249. set: function (value) {
  45250. if (StandardMaterial._EmissiveTextureEnabled === value) {
  45251. return;
  45252. }
  45253. StandardMaterial._EmissiveTextureEnabled = value;
  45254. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45255. },
  45256. enumerable: true,
  45257. configurable: true
  45258. });
  45259. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  45260. get: function () {
  45261. return StandardMaterial._SpecularTextureEnabled;
  45262. },
  45263. set: function (value) {
  45264. if (StandardMaterial._SpecularTextureEnabled === value) {
  45265. return;
  45266. }
  45267. StandardMaterial._SpecularTextureEnabled = value;
  45268. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45269. },
  45270. enumerable: true,
  45271. configurable: true
  45272. });
  45273. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  45274. get: function () {
  45275. return StandardMaterial._BumpTextureEnabled;
  45276. },
  45277. set: function (value) {
  45278. if (StandardMaterial._BumpTextureEnabled === value) {
  45279. return;
  45280. }
  45281. StandardMaterial._BumpTextureEnabled = value;
  45282. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45283. },
  45284. enumerable: true,
  45285. configurable: true
  45286. });
  45287. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  45288. get: function () {
  45289. return StandardMaterial._LightmapTextureEnabled;
  45290. },
  45291. set: function (value) {
  45292. if (StandardMaterial._LightmapTextureEnabled === value) {
  45293. return;
  45294. }
  45295. StandardMaterial._LightmapTextureEnabled = value;
  45296. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45297. },
  45298. enumerable: true,
  45299. configurable: true
  45300. });
  45301. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  45302. get: function () {
  45303. return StandardMaterial._RefractionTextureEnabled;
  45304. },
  45305. set: function (value) {
  45306. if (StandardMaterial._RefractionTextureEnabled === value) {
  45307. return;
  45308. }
  45309. StandardMaterial._RefractionTextureEnabled = value;
  45310. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45311. },
  45312. enumerable: true,
  45313. configurable: true
  45314. });
  45315. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  45316. get: function () {
  45317. return StandardMaterial._ColorGradingTextureEnabled;
  45318. },
  45319. set: function (value) {
  45320. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  45321. return;
  45322. }
  45323. StandardMaterial._ColorGradingTextureEnabled = value;
  45324. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45325. },
  45326. enumerable: true,
  45327. configurable: true
  45328. });
  45329. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  45330. get: function () {
  45331. return StandardMaterial._FresnelEnabled;
  45332. },
  45333. set: function (value) {
  45334. if (StandardMaterial._FresnelEnabled === value) {
  45335. return;
  45336. }
  45337. StandardMaterial._FresnelEnabled = value;
  45338. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  45339. },
  45340. enumerable: true,
  45341. configurable: true
  45342. });
  45343. // Flags used to enable or disable a type of texture for all Standard Materials
  45344. StandardMaterial._DiffuseTextureEnabled = true;
  45345. StandardMaterial._AmbientTextureEnabled = true;
  45346. StandardMaterial._OpacityTextureEnabled = true;
  45347. StandardMaterial._ReflectionTextureEnabled = true;
  45348. StandardMaterial._EmissiveTextureEnabled = true;
  45349. StandardMaterial._SpecularTextureEnabled = true;
  45350. StandardMaterial._BumpTextureEnabled = true;
  45351. StandardMaterial._LightmapTextureEnabled = true;
  45352. StandardMaterial._RefractionTextureEnabled = true;
  45353. StandardMaterial._ColorGradingTextureEnabled = true;
  45354. StandardMaterial._FresnelEnabled = true;
  45355. __decorate([
  45356. BABYLON.serializeAsTexture("diffuseTexture")
  45357. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  45358. __decorate([
  45359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45360. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  45361. __decorate([
  45362. BABYLON.serializeAsTexture("ambientTexture")
  45363. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  45364. __decorate([
  45365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45366. ], StandardMaterial.prototype, "ambientTexture", void 0);
  45367. __decorate([
  45368. BABYLON.serializeAsTexture("opacityTexture")
  45369. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  45370. __decorate([
  45371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45372. ], StandardMaterial.prototype, "opacityTexture", void 0);
  45373. __decorate([
  45374. BABYLON.serializeAsTexture("reflectionTexture")
  45375. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  45376. __decorate([
  45377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45378. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  45379. __decorate([
  45380. BABYLON.serializeAsTexture("emissiveTexture")
  45381. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  45382. __decorate([
  45383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45384. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  45385. __decorate([
  45386. BABYLON.serializeAsTexture("specularTexture")
  45387. ], StandardMaterial.prototype, "_specularTexture", void 0);
  45388. __decorate([
  45389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45390. ], StandardMaterial.prototype, "specularTexture", void 0);
  45391. __decorate([
  45392. BABYLON.serializeAsTexture("bumpTexture")
  45393. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  45394. __decorate([
  45395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45396. ], StandardMaterial.prototype, "bumpTexture", void 0);
  45397. __decorate([
  45398. BABYLON.serializeAsTexture("lightmapTexture")
  45399. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  45400. __decorate([
  45401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45402. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  45403. __decorate([
  45404. BABYLON.serializeAsTexture("refractionTexture")
  45405. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  45406. __decorate([
  45407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45408. ], StandardMaterial.prototype, "refractionTexture", void 0);
  45409. __decorate([
  45410. BABYLON.serializeAsColor3("ambient")
  45411. ], StandardMaterial.prototype, "ambientColor", void 0);
  45412. __decorate([
  45413. BABYLON.serializeAsColor3("diffuse")
  45414. ], StandardMaterial.prototype, "diffuseColor", void 0);
  45415. __decorate([
  45416. BABYLON.serializeAsColor3("specular")
  45417. ], StandardMaterial.prototype, "specularColor", void 0);
  45418. __decorate([
  45419. BABYLON.serializeAsColor3("emissive")
  45420. ], StandardMaterial.prototype, "emissiveColor", void 0);
  45421. __decorate([
  45422. BABYLON.serialize()
  45423. ], StandardMaterial.prototype, "specularPower", void 0);
  45424. __decorate([
  45425. BABYLON.serialize("useAlphaFromDiffuseTexture")
  45426. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  45427. __decorate([
  45428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45429. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  45430. __decorate([
  45431. BABYLON.serialize("useEmissiveAsIllumination")
  45432. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  45433. __decorate([
  45434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45435. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  45436. __decorate([
  45437. BABYLON.serialize("linkEmissiveWithDiffuse")
  45438. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  45439. __decorate([
  45440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45441. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  45442. __decorate([
  45443. BABYLON.serialize("useSpecularOverAlpha")
  45444. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  45445. __decorate([
  45446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45447. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  45448. __decorate([
  45449. BABYLON.serialize("useReflectionOverAlpha")
  45450. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  45451. __decorate([
  45452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45453. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  45454. __decorate([
  45455. BABYLON.serialize("disableLighting")
  45456. ], StandardMaterial.prototype, "_disableLighting", void 0);
  45457. __decorate([
  45458. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45459. ], StandardMaterial.prototype, "disableLighting", void 0);
  45460. __decorate([
  45461. BABYLON.serialize("useParallax")
  45462. ], StandardMaterial.prototype, "_useParallax", void 0);
  45463. __decorate([
  45464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45465. ], StandardMaterial.prototype, "useParallax", void 0);
  45466. __decorate([
  45467. BABYLON.serialize("useParallaxOcclusion")
  45468. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  45469. __decorate([
  45470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45471. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  45472. __decorate([
  45473. BABYLON.serialize()
  45474. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  45475. __decorate([
  45476. BABYLON.serialize("roughness")
  45477. ], StandardMaterial.prototype, "_roughness", void 0);
  45478. __decorate([
  45479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45480. ], StandardMaterial.prototype, "roughness", void 0);
  45481. __decorate([
  45482. BABYLON.serialize()
  45483. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  45484. __decorate([
  45485. BABYLON.serialize()
  45486. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  45487. __decorate([
  45488. BABYLON.serialize("useLightmapAsShadowmap")
  45489. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  45490. __decorate([
  45491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45492. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45493. __decorate([
  45494. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  45495. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  45496. __decorate([
  45497. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45498. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  45499. __decorate([
  45500. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  45501. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  45502. __decorate([
  45503. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45504. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  45505. __decorate([
  45506. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  45507. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  45508. __decorate([
  45509. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45510. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  45511. __decorate([
  45512. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  45513. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  45514. __decorate([
  45515. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45516. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  45517. __decorate([
  45518. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  45519. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  45520. __decorate([
  45521. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45522. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  45523. __decorate([
  45524. BABYLON.serialize("useReflectionFresnelFromSpecular")
  45525. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  45526. __decorate([
  45527. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45528. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  45529. __decorate([
  45530. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  45531. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  45532. __decorate([
  45533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45534. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  45535. __decorate([
  45536. BABYLON.serialize("maxSimultaneousLights")
  45537. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  45538. __decorate([
  45539. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45540. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  45541. __decorate([
  45542. BABYLON.serialize("invertNormalMapX")
  45543. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  45544. __decorate([
  45545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45546. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  45547. __decorate([
  45548. BABYLON.serialize("invertNormalMapY")
  45549. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  45550. __decorate([
  45551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45552. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  45553. __decorate([
  45554. BABYLON.serialize("twoSidedLighting")
  45555. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  45556. __decorate([
  45557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45558. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  45559. __decorate([
  45560. BABYLON.serialize()
  45561. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  45562. return StandardMaterial;
  45563. }(BABYLON.PushMaterial));
  45564. BABYLON.StandardMaterial = StandardMaterial;
  45565. })(BABYLON || (BABYLON = {}));
  45566. //# sourceMappingURL=babylon.standardMaterial.js.map
  45567. var BABYLON;
  45568. (function (BABYLON) {
  45569. /**
  45570. * This class implement a typical dictionary using a string as key and the generic type T as value.
  45571. * The underlying implementation relies on an associative array to ensure the best performances.
  45572. * The value can be anything including 'null' but except 'undefined'
  45573. */
  45574. var StringDictionary = (function () {
  45575. function StringDictionary() {
  45576. this._count = 0;
  45577. this._data = {};
  45578. }
  45579. /**
  45580. * This will clear this dictionary and copy the content from the 'source' one.
  45581. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  45582. * @param source the dictionary to take the content from and copy to this dictionary
  45583. */
  45584. StringDictionary.prototype.copyFrom = function (source) {
  45585. var _this = this;
  45586. this.clear();
  45587. source.forEach(function (t, v) { return _this.add(t, v); });
  45588. };
  45589. /**
  45590. * Get a value based from its key
  45591. * @param key the given key to get the matching value from
  45592. * @return the value if found, otherwise undefined is returned
  45593. */
  45594. StringDictionary.prototype.get = function (key) {
  45595. var val = this._data[key];
  45596. if (val !== undefined) {
  45597. return val;
  45598. }
  45599. return undefined;
  45600. };
  45601. /**
  45602. * Get a value from its key or add it if it doesn't exist.
  45603. * This method will ensure you that a given key/data will be present in the dictionary.
  45604. * @param key the given key to get the matching value from
  45605. * @param factory the factory that will create the value if the key is not present in the dictionary.
  45606. * The factory will only be invoked if there's no data for the given key.
  45607. * @return the value corresponding to the key.
  45608. */
  45609. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  45610. var val = this.get(key);
  45611. if (val !== undefined) {
  45612. return val;
  45613. }
  45614. val = factory(key);
  45615. if (val) {
  45616. this.add(key, val);
  45617. }
  45618. return val;
  45619. };
  45620. /**
  45621. * Get a value from its key if present in the dictionary otherwise add it
  45622. * @param key the key to get the value from
  45623. * @param val if there's no such key/value pair in the dictionary add it with this value
  45624. * @return the value corresponding to the key
  45625. */
  45626. StringDictionary.prototype.getOrAdd = function (key, val) {
  45627. var curVal = this.get(key);
  45628. if (curVal !== undefined) {
  45629. return curVal;
  45630. }
  45631. this.add(key, val);
  45632. return val;
  45633. };
  45634. /**
  45635. * Check if there's a given key in the dictionary
  45636. * @param key the key to check for
  45637. * @return true if the key is present, false otherwise
  45638. */
  45639. StringDictionary.prototype.contains = function (key) {
  45640. return this._data[key] !== undefined;
  45641. };
  45642. /**
  45643. * Add a new key and its corresponding value
  45644. * @param key the key to add
  45645. * @param value the value corresponding to the key
  45646. * @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
  45647. */
  45648. StringDictionary.prototype.add = function (key, value) {
  45649. if (this._data[key] !== undefined) {
  45650. return false;
  45651. }
  45652. this._data[key] = value;
  45653. ++this._count;
  45654. return true;
  45655. };
  45656. StringDictionary.prototype.set = function (key, value) {
  45657. if (this._data[key] === undefined) {
  45658. return false;
  45659. }
  45660. this._data[key] = value;
  45661. return true;
  45662. };
  45663. /**
  45664. * Get the element of the given key and remove it from the dictionary
  45665. * @param key
  45666. */
  45667. StringDictionary.prototype.getAndRemove = function (key) {
  45668. var val = this.get(key);
  45669. if (val !== undefined) {
  45670. delete this._data[key];
  45671. --this._count;
  45672. return val;
  45673. }
  45674. return null;
  45675. };
  45676. /**
  45677. * Remove a key/value from the dictionary.
  45678. * @param key the key to remove
  45679. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  45680. */
  45681. StringDictionary.prototype.remove = function (key) {
  45682. if (this.contains(key)) {
  45683. delete this._data[key];
  45684. --this._count;
  45685. return true;
  45686. }
  45687. return false;
  45688. };
  45689. /**
  45690. * Clear the whole content of the dictionary
  45691. */
  45692. StringDictionary.prototype.clear = function () {
  45693. this._data = {};
  45694. this._count = 0;
  45695. };
  45696. Object.defineProperty(StringDictionary.prototype, "count", {
  45697. get: function () {
  45698. return this._count;
  45699. },
  45700. enumerable: true,
  45701. configurable: true
  45702. });
  45703. /**
  45704. * Execute a callback on each key/val of the dictionary.
  45705. * Note that you can remove any element in this dictionary in the callback implementation
  45706. * @param callback the callback to execute on a given key/value pair
  45707. */
  45708. StringDictionary.prototype.forEach = function (callback) {
  45709. for (var cur in this._data) {
  45710. var val = this._data[cur];
  45711. callback(cur, val);
  45712. }
  45713. };
  45714. /**
  45715. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  45716. * If the callback returns null or undefined the method will iterate to the next key/value pair
  45717. * Note that you can remove any element in this dictionary in the callback implementation
  45718. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  45719. */
  45720. StringDictionary.prototype.first = function (callback) {
  45721. for (var cur in this._data) {
  45722. var val = this._data[cur];
  45723. var res = callback(cur, val);
  45724. if (res) {
  45725. return res;
  45726. }
  45727. }
  45728. return null;
  45729. };
  45730. return StringDictionary;
  45731. }());
  45732. BABYLON.StringDictionary = StringDictionary;
  45733. })(BABYLON || (BABYLON = {}));
  45734. //# sourceMappingURL=babylon.stringDictionary.js.map
  45735. var BABYLON;
  45736. (function (BABYLON) {
  45737. var DynamicFloatArrayElementInfo = (function () {
  45738. function DynamicFloatArrayElementInfo() {
  45739. }
  45740. return DynamicFloatArrayElementInfo;
  45741. }());
  45742. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  45743. /**
  45744. * 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.
  45745. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  45746. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  45747. * 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.
  45748. * 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.
  45749. * 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".
  45750. */
  45751. var DynamicFloatArray = (function () {
  45752. /**
  45753. * Construct an instance of the dynamic float array
  45754. * @param stride size of one element in float (i.e. not bytes!)
  45755. * @param initialElementCount the number of available entries at construction
  45756. */
  45757. function DynamicFloatArray(stride, initialElementCount) {
  45758. this.compareValueOffset = null;
  45759. this.sortingAscending = true;
  45760. this._stride = stride;
  45761. this.buffer = new Float32Array(stride * initialElementCount);
  45762. this._lastUsed = 0;
  45763. this._firstFree = 0;
  45764. this._allEntries = new Array(initialElementCount);
  45765. this._freeEntries = new Array(initialElementCount);
  45766. for (var i = 0; i < initialElementCount; i++) {
  45767. var element = new DynamicFloatArrayElementInfo();
  45768. element.offset = i * stride;
  45769. this._allEntries[i] = element;
  45770. this._freeEntries[initialElementCount - i - 1] = element;
  45771. }
  45772. }
  45773. /**
  45774. * Allocate an element in the array.
  45775. * @return the element info instance that contains the offset into the main buffer of the element's location.
  45776. * Beware, this offset may change when you call pack()
  45777. */
  45778. DynamicFloatArray.prototype.allocElement = function () {
  45779. if (this._freeEntries.length === 0) {
  45780. this._growBuffer();
  45781. }
  45782. var el = this._freeEntries.pop();
  45783. this._lastUsed = Math.max(el.offset, this._lastUsed);
  45784. if (el.offset === this._firstFree) {
  45785. if (this._freeEntries.length > 0) {
  45786. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  45787. }
  45788. else {
  45789. this._firstFree += this._stride;
  45790. }
  45791. }
  45792. return el;
  45793. };
  45794. /**
  45795. * Free the element corresponding to the given element info
  45796. * @param elInfo the element that describe the allocated element
  45797. */
  45798. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  45799. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  45800. this._freeEntries.push(elInfo);
  45801. };
  45802. /**
  45803. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  45804. * 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().
  45805. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  45806. */
  45807. DynamicFloatArray.prototype.pack = function () {
  45808. // no free slot? no need to pack
  45809. if (this._freeEntries.length === 0) {
  45810. return this.buffer;
  45811. }
  45812. // If the buffer is already packed the last used will always be lower than the first free
  45813. // 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.
  45814. if (this._lastUsed < this._firstFree) {
  45815. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  45816. return elementsBuffer_1;
  45817. }
  45818. var s = this._stride;
  45819. // 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
  45820. var lastFree = new DynamicFloatArrayElementInfo();
  45821. lastFree.offset = this.totalElementCount * s;
  45822. this._freeEntries.push(lastFree);
  45823. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  45824. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  45825. var firstFreeSlotOffset = sortedFree[0].offset;
  45826. var freeZoneSize = 1;
  45827. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  45828. var prevOffset = sortedFree[0].offset;
  45829. for (var i = 1; i < sortedFree.length; i++) {
  45830. // 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
  45831. if (firstFreeSlotOffset >= occupiedZoneSize) {
  45832. break;
  45833. }
  45834. var curFree = sortedFree[i];
  45835. var curOffset = curFree.offset;
  45836. // Compute the distance between this offset and the previous
  45837. var distance = curOffset - prevOffset;
  45838. // If the distance is the stride size, they are adjacent, it good, move to the next
  45839. if (distance === s) {
  45840. // Free zone is one element bigger
  45841. ++freeZoneSize;
  45842. // as we're about to iterate to the next, the cur becomes the previous...
  45843. prevOffset = curOffset;
  45844. continue;
  45845. }
  45846. // Distance is bigger, which means there's x element between the previous free and this one
  45847. var usedRange = (distance / s) - 1;
  45848. // Two cases the free zone is smaller than the data to move or bigger
  45849. // Copy what can fit in the free zone
  45850. var curMoveOffset = curOffset - s;
  45851. var copyCount = Math.min(freeZoneSize, usedRange);
  45852. for (var j = 0; j < copyCount; j++) {
  45853. var freeI = firstFreeSlotOffset / s;
  45854. var curI = curMoveOffset / s;
  45855. var moveEl = sortedAll[curI];
  45856. this._moveElement(moveEl, firstFreeSlotOffset);
  45857. var replacedEl = sortedAll[freeI];
  45858. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  45859. replacedEl.offset = curMoveOffset;
  45860. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  45861. sortedAll[freeI] = moveEl;
  45862. sortedAll[curI] = replacedEl;
  45863. curMoveOffset -= s;
  45864. firstFreeSlotOffset += s;
  45865. }
  45866. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  45867. if (freeZoneSize <= usedRange) {
  45868. firstFreeSlotOffset = curMoveOffset + s;
  45869. freeZoneSize = 1 + copyCount;
  45870. }
  45871. else {
  45872. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  45873. }
  45874. // as we're about to iterate to the next, the cur becomes the previous...
  45875. prevOffset = curOffset;
  45876. }
  45877. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  45878. this._lastUsed = firstFreeSlotOffset - s;
  45879. this._firstFree = firstFreeSlotOffset;
  45880. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  45881. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  45882. this._allEntries = sortedAll;
  45883. return elementsBuffer;
  45884. };
  45885. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  45886. for (var i = 0; i < this._stride; i++) {
  45887. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  45888. }
  45889. element.offset = destOffset;
  45890. };
  45891. DynamicFloatArray.prototype._growBuffer = function () {
  45892. // Allocate the new buffer with 50% more entries, copy the content of the current one
  45893. var newElCount = Math.floor(this.totalElementCount * 1.5);
  45894. var newBuffer = new Float32Array(newElCount * this._stride);
  45895. newBuffer.set(this.buffer);
  45896. var curCount = this.totalElementCount;
  45897. var addedCount = newElCount - this.totalElementCount;
  45898. for (var i = 0; i < addedCount; i++) {
  45899. var element = new DynamicFloatArrayElementInfo();
  45900. element.offset = (curCount + i) * this.stride;
  45901. this._allEntries.push(element);
  45902. this._freeEntries[addedCount - i - 1] = element;
  45903. }
  45904. this._firstFree = curCount * this.stride;
  45905. this.buffer = newBuffer;
  45906. };
  45907. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  45908. /**
  45909. * Get the total count of entries that can fit in the current buffer
  45910. * @returns the elements count
  45911. */
  45912. get: function () {
  45913. return this._allEntries.length;
  45914. },
  45915. enumerable: true,
  45916. configurable: true
  45917. });
  45918. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  45919. /**
  45920. * Get the count of free entries that can still be allocated without resizing the buffer
  45921. * @returns the free elements count
  45922. */
  45923. get: function () {
  45924. return this._freeEntries.length;
  45925. },
  45926. enumerable: true,
  45927. configurable: true
  45928. });
  45929. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  45930. /**
  45931. * Get the count of allocated elements
  45932. * @returns the allocated elements count
  45933. */
  45934. get: function () {
  45935. return this._allEntries.length - this._freeEntries.length;
  45936. },
  45937. enumerable: true,
  45938. configurable: true
  45939. });
  45940. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  45941. /**
  45942. * Return the size of one element in float
  45943. * @returns the size in float
  45944. */
  45945. get: function () {
  45946. return this._stride;
  45947. },
  45948. enumerable: true,
  45949. configurable: true
  45950. });
  45951. DynamicFloatArray.prototype.sort = function () {
  45952. var _this = this;
  45953. if (!this.compareValueOffset) {
  45954. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  45955. }
  45956. var count = this.usedElementCount;
  45957. // Do we have to (re)create the sort table?
  45958. if (!this._sortTable || this._sortTable.length < count) {
  45959. // 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...
  45960. var newCount = Math.min(this.totalElementCount, count * 2);
  45961. this._sortTable = new Array(newCount);
  45962. }
  45963. if (!this._sortedTable || this._sortedTable.length !== count) {
  45964. this._sortedTable = new Array(count);
  45965. }
  45966. // Because, you know...
  45967. this.pack();
  45968. //let stride = this.stride;
  45969. //for (let i = 0; i < count; i++) {
  45970. // let si = this._sortTable[i];
  45971. // if (!si) {
  45972. // si = new SortInfo();
  45973. // this._sortTable[i] = si;
  45974. // }
  45975. // si.entry = this._allEntries[i];
  45976. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  45977. // si.swapedOffset = null;
  45978. // this._sortedTable[i] = si;
  45979. //}
  45980. var curOffset = 0;
  45981. var stride = this.stride;
  45982. for (var i = 0; i < count; i++, curOffset += stride) {
  45983. var si = this._sortTable[i];
  45984. if (!si) {
  45985. si = new SortInfo();
  45986. this._sortTable[i] = si;
  45987. }
  45988. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  45989. si.offset = curOffset;
  45990. si.swapedOffset = null;
  45991. this._sortedTable[i] = si;
  45992. }
  45993. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  45994. if (this.sortingAscending) {
  45995. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  45996. }
  45997. else {
  45998. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  45999. }
  46000. var swapElements = function (src, dst) {
  46001. for (var i = 0; i < stride; i++) {
  46002. var tps = _this.buffer[dst + i];
  46003. _this.buffer[dst + i] = _this.buffer[src + i];
  46004. _this.buffer[src + i] = tps;
  46005. }
  46006. };
  46007. // 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:
  46008. // 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),
  46009. // and I still want something with a good algorithm complexity.
  46010. // 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,
  46011. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  46012. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  46013. // 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
  46014. // until we find a SortInfo object without a swapedOffset which means we got the right location
  46015. // 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
  46016. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  46017. for (var i = 0; i < count; i++) {
  46018. // Get the element to move
  46019. var sourceSI = this._sortedTable[i];
  46020. var destSI = this._sortTable[i];
  46021. var sourceOff = sourceSI.offset;
  46022. // If the source changed location, find the new one
  46023. if (sourceSI.swapedOffset) {
  46024. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  46025. var curSI = sourceSI;
  46026. while (curSI.swapedOffset) {
  46027. curSI = this._sortTable[curSI.swapedOffset / stride];
  46028. }
  46029. // Finally get the right location
  46030. sourceOff = curSI.offset;
  46031. }
  46032. // Tag the element being replaced with its new location
  46033. destSI.swapedOffset = sourceOff;
  46034. // Swap elements (only if needed)
  46035. if (sourceOff !== destSI.offset) {
  46036. swapElements(sourceOff, destSI.offset);
  46037. }
  46038. // Update the offset in the corresponding DFAE
  46039. //sourceSI.entry.offset = destSI.entry.offset;
  46040. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  46041. }
  46042. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  46043. return true;
  46044. };
  46045. return DynamicFloatArray;
  46046. }());
  46047. BABYLON.DynamicFloatArray = DynamicFloatArray;
  46048. var SortInfo = (function () {
  46049. function SortInfo() {
  46050. this.compareData = this.offset = this.swapedOffset = null;
  46051. }
  46052. return SortInfo;
  46053. }());
  46054. })(BABYLON || (BABYLON = {}));
  46055. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  46056. var BABYLON;
  46057. (function (BABYLON) {
  46058. var Condition = (function () {
  46059. function Condition(actionManager) {
  46060. this._actionManager = actionManager;
  46061. }
  46062. Condition.prototype.isValid = function () {
  46063. return true;
  46064. };
  46065. Condition.prototype._getProperty = function (propertyPath) {
  46066. return this._actionManager._getProperty(propertyPath);
  46067. };
  46068. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  46069. return this._actionManager._getEffectiveTarget(target, propertyPath);
  46070. };
  46071. Condition.prototype.serialize = function () {
  46072. };
  46073. Condition.prototype._serialize = function (serializedCondition) {
  46074. return {
  46075. type: 2,
  46076. children: [],
  46077. name: serializedCondition.name,
  46078. properties: serializedCondition.properties
  46079. };
  46080. };
  46081. return Condition;
  46082. }());
  46083. BABYLON.Condition = Condition;
  46084. var ValueCondition = (function (_super) {
  46085. __extends(ValueCondition, _super);
  46086. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  46087. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  46088. var _this = _super.call(this, actionManager) || this;
  46089. _this.propertyPath = propertyPath;
  46090. _this.value = value;
  46091. _this.operator = operator;
  46092. _this._target = target;
  46093. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  46094. _this._property = _this._getProperty(_this.propertyPath);
  46095. return _this;
  46096. }
  46097. Object.defineProperty(ValueCondition, "IsEqual", {
  46098. get: function () {
  46099. return ValueCondition._IsEqual;
  46100. },
  46101. enumerable: true,
  46102. configurable: true
  46103. });
  46104. Object.defineProperty(ValueCondition, "IsDifferent", {
  46105. get: function () {
  46106. return ValueCondition._IsDifferent;
  46107. },
  46108. enumerable: true,
  46109. configurable: true
  46110. });
  46111. Object.defineProperty(ValueCondition, "IsGreater", {
  46112. get: function () {
  46113. return ValueCondition._IsGreater;
  46114. },
  46115. enumerable: true,
  46116. configurable: true
  46117. });
  46118. Object.defineProperty(ValueCondition, "IsLesser", {
  46119. get: function () {
  46120. return ValueCondition._IsLesser;
  46121. },
  46122. enumerable: true,
  46123. configurable: true
  46124. });
  46125. // Methods
  46126. ValueCondition.prototype.isValid = function () {
  46127. switch (this.operator) {
  46128. case ValueCondition.IsGreater:
  46129. return this._effectiveTarget[this._property] > this.value;
  46130. case ValueCondition.IsLesser:
  46131. return this._effectiveTarget[this._property] < this.value;
  46132. case ValueCondition.IsEqual:
  46133. case ValueCondition.IsDifferent:
  46134. var check;
  46135. if (this.value.equals) {
  46136. check = this.value.equals(this._effectiveTarget[this._property]);
  46137. }
  46138. else {
  46139. check = this.value === this._effectiveTarget[this._property];
  46140. }
  46141. return this.operator === ValueCondition.IsEqual ? check : !check;
  46142. }
  46143. return false;
  46144. };
  46145. ValueCondition.prototype.serialize = function () {
  46146. return this._serialize({
  46147. name: "ValueCondition",
  46148. properties: [
  46149. BABYLON.Action._GetTargetProperty(this._target),
  46150. { name: "propertyPath", value: this.propertyPath },
  46151. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46152. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  46153. ]
  46154. });
  46155. };
  46156. ValueCondition.GetOperatorName = function (operator) {
  46157. switch (operator) {
  46158. case ValueCondition._IsEqual: return "IsEqual";
  46159. case ValueCondition._IsDifferent: return "IsDifferent";
  46160. case ValueCondition._IsGreater: return "IsGreater";
  46161. case ValueCondition._IsLesser: return "IsLesser";
  46162. default: return "";
  46163. }
  46164. };
  46165. // Statics
  46166. ValueCondition._IsEqual = 0;
  46167. ValueCondition._IsDifferent = 1;
  46168. ValueCondition._IsGreater = 2;
  46169. ValueCondition._IsLesser = 3;
  46170. return ValueCondition;
  46171. }(Condition));
  46172. BABYLON.ValueCondition = ValueCondition;
  46173. var PredicateCondition = (function (_super) {
  46174. __extends(PredicateCondition, _super);
  46175. function PredicateCondition(actionManager, predicate) {
  46176. var _this = _super.call(this, actionManager) || this;
  46177. _this.predicate = predicate;
  46178. return _this;
  46179. }
  46180. PredicateCondition.prototype.isValid = function () {
  46181. return this.predicate();
  46182. };
  46183. return PredicateCondition;
  46184. }(Condition));
  46185. BABYLON.PredicateCondition = PredicateCondition;
  46186. var StateCondition = (function (_super) {
  46187. __extends(StateCondition, _super);
  46188. function StateCondition(actionManager, target, value) {
  46189. var _this = _super.call(this, actionManager) || this;
  46190. _this.value = value;
  46191. _this._target = target;
  46192. return _this;
  46193. }
  46194. // Methods
  46195. StateCondition.prototype.isValid = function () {
  46196. return this._target.state === this.value;
  46197. };
  46198. StateCondition.prototype.serialize = function () {
  46199. return this._serialize({
  46200. name: "StateCondition",
  46201. properties: [
  46202. BABYLON.Action._GetTargetProperty(this._target),
  46203. { name: "value", value: this.value }
  46204. ]
  46205. });
  46206. };
  46207. return StateCondition;
  46208. }(Condition));
  46209. BABYLON.StateCondition = StateCondition;
  46210. })(BABYLON || (BABYLON = {}));
  46211. //# sourceMappingURL=babylon.condition.js.map
  46212. var BABYLON;
  46213. (function (BABYLON) {
  46214. var Action = (function () {
  46215. function Action(triggerOptions, condition) {
  46216. this.triggerOptions = triggerOptions;
  46217. if (triggerOptions.parameter) {
  46218. this.trigger = triggerOptions.trigger;
  46219. this._triggerParameter = triggerOptions.parameter;
  46220. }
  46221. else {
  46222. this.trigger = triggerOptions;
  46223. }
  46224. this._nextActiveAction = this;
  46225. this._condition = condition;
  46226. }
  46227. // Methods
  46228. Action.prototype._prepare = function () {
  46229. };
  46230. Action.prototype.getTriggerParameter = function () {
  46231. return this._triggerParameter;
  46232. };
  46233. Action.prototype._executeCurrent = function (evt) {
  46234. if (this._nextActiveAction._condition) {
  46235. var condition = this._nextActiveAction._condition;
  46236. var currentRenderId = this._actionManager.getScene().getRenderId();
  46237. // We cache the current evaluation for the current frame
  46238. if (condition._evaluationId === currentRenderId) {
  46239. if (!condition._currentResult) {
  46240. return;
  46241. }
  46242. }
  46243. else {
  46244. condition._evaluationId = currentRenderId;
  46245. if (!condition.isValid()) {
  46246. condition._currentResult = false;
  46247. return;
  46248. }
  46249. condition._currentResult = true;
  46250. }
  46251. }
  46252. this._nextActiveAction.execute(evt);
  46253. this.skipToNextActiveAction();
  46254. };
  46255. Action.prototype.execute = function (evt) {
  46256. };
  46257. Action.prototype.skipToNextActiveAction = function () {
  46258. if (this._nextActiveAction._child) {
  46259. if (!this._nextActiveAction._child._actionManager) {
  46260. this._nextActiveAction._child._actionManager = this._actionManager;
  46261. }
  46262. this._nextActiveAction = this._nextActiveAction._child;
  46263. }
  46264. else {
  46265. this._nextActiveAction = this;
  46266. }
  46267. };
  46268. Action.prototype.then = function (action) {
  46269. this._child = action;
  46270. action._actionManager = this._actionManager;
  46271. action._prepare();
  46272. return action;
  46273. };
  46274. Action.prototype._getProperty = function (propertyPath) {
  46275. return this._actionManager._getProperty(propertyPath);
  46276. };
  46277. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  46278. return this._actionManager._getEffectiveTarget(target, propertyPath);
  46279. };
  46280. Action.prototype.serialize = function (parent) {
  46281. };
  46282. // Called by BABYLON.Action objects in serialize(...). Internal use
  46283. Action.prototype._serialize = function (serializedAction, parent) {
  46284. var serializationObject = {
  46285. type: 1,
  46286. children: [],
  46287. name: serializedAction.name,
  46288. properties: serializedAction.properties || []
  46289. };
  46290. // Serialize child
  46291. if (this._child) {
  46292. this._child.serialize(serializationObject);
  46293. }
  46294. // Check if "this" has a condition
  46295. if (this._condition) {
  46296. var serializedCondition = this._condition.serialize();
  46297. serializedCondition.children.push(serializationObject);
  46298. if (parent) {
  46299. parent.children.push(serializedCondition);
  46300. }
  46301. return serializedCondition;
  46302. }
  46303. if (parent) {
  46304. parent.children.push(serializationObject);
  46305. }
  46306. return serializationObject;
  46307. };
  46308. Action._SerializeValueAsString = function (value) {
  46309. if (typeof value === "number") {
  46310. return value.toString();
  46311. }
  46312. if (typeof value === "boolean") {
  46313. return value ? "true" : "false";
  46314. }
  46315. if (value instanceof BABYLON.Vector2) {
  46316. return value.x + ", " + value.y;
  46317. }
  46318. if (value instanceof BABYLON.Vector3) {
  46319. return value.x + ", " + value.y + ", " + value.z;
  46320. }
  46321. if (value instanceof BABYLON.Color3) {
  46322. return value.r + ", " + value.g + ", " + value.b;
  46323. }
  46324. if (value instanceof BABYLON.Color4) {
  46325. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  46326. }
  46327. return value; // string
  46328. };
  46329. Action._GetTargetProperty = function (target) {
  46330. return {
  46331. name: "target",
  46332. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  46333. : target instanceof BABYLON.Light ? "LightProperties"
  46334. : target instanceof BABYLON.Camera ? "CameraProperties"
  46335. : "SceneProperties",
  46336. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  46337. };
  46338. };
  46339. return Action;
  46340. }());
  46341. BABYLON.Action = Action;
  46342. })(BABYLON || (BABYLON = {}));
  46343. //# sourceMappingURL=babylon.action.js.map
  46344. var BABYLON;
  46345. (function (BABYLON) {
  46346. /**
  46347. * ActionEvent is the event beint sent when an action is triggered.
  46348. */
  46349. var ActionEvent = (function () {
  46350. /**
  46351. * @param source The mesh or sprite that triggered the action.
  46352. * @param pointerX The X mouse cursor position at the time of the event
  46353. * @param pointerY The Y mouse cursor position at the time of the event
  46354. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  46355. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  46356. */
  46357. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  46358. this.source = source;
  46359. this.pointerX = pointerX;
  46360. this.pointerY = pointerY;
  46361. this.meshUnderPointer = meshUnderPointer;
  46362. this.sourceEvent = sourceEvent;
  46363. this.additionalData = additionalData;
  46364. }
  46365. /**
  46366. * Helper function to auto-create an ActionEvent from a source mesh.
  46367. * @param source The source mesh that triggered the event
  46368. * @param evt {Event} The original (browser) event
  46369. */
  46370. ActionEvent.CreateNew = function (source, evt, additionalData) {
  46371. var scene = source.getScene();
  46372. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  46373. };
  46374. /**
  46375. * Helper function to auto-create an ActionEvent from a source mesh.
  46376. * @param source The source sprite that triggered the event
  46377. * @param scene Scene associated with the sprite
  46378. * @param evt {Event} The original (browser) event
  46379. */
  46380. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  46381. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  46382. };
  46383. /**
  46384. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  46385. * @param scene the scene where the event occurred
  46386. * @param evt {Event} The original (browser) event
  46387. */
  46388. ActionEvent.CreateNewFromScene = function (scene, evt) {
  46389. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  46390. };
  46391. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  46392. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  46393. };
  46394. return ActionEvent;
  46395. }());
  46396. BABYLON.ActionEvent = ActionEvent;
  46397. /**
  46398. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  46399. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  46400. */
  46401. var ActionManager = (function () {
  46402. function ActionManager(scene) {
  46403. // Members
  46404. this.actions = new Array();
  46405. this.hoverCursor = '';
  46406. this._scene = scene;
  46407. scene._actionManagers.push(this);
  46408. }
  46409. Object.defineProperty(ActionManager, "NothingTrigger", {
  46410. get: function () {
  46411. return ActionManager._NothingTrigger;
  46412. },
  46413. enumerable: true,
  46414. configurable: true
  46415. });
  46416. Object.defineProperty(ActionManager, "OnPickTrigger", {
  46417. get: function () {
  46418. return ActionManager._OnPickTrigger;
  46419. },
  46420. enumerable: true,
  46421. configurable: true
  46422. });
  46423. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  46424. get: function () {
  46425. return ActionManager._OnLeftPickTrigger;
  46426. },
  46427. enumerable: true,
  46428. configurable: true
  46429. });
  46430. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  46431. get: function () {
  46432. return ActionManager._OnRightPickTrigger;
  46433. },
  46434. enumerable: true,
  46435. configurable: true
  46436. });
  46437. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  46438. get: function () {
  46439. return ActionManager._OnCenterPickTrigger;
  46440. },
  46441. enumerable: true,
  46442. configurable: true
  46443. });
  46444. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  46445. get: function () {
  46446. return ActionManager._OnPickDownTrigger;
  46447. },
  46448. enumerable: true,
  46449. configurable: true
  46450. });
  46451. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  46452. get: function () {
  46453. return ActionManager._OnDoublePickTrigger;
  46454. },
  46455. enumerable: true,
  46456. configurable: true
  46457. });
  46458. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  46459. get: function () {
  46460. return ActionManager._OnPickUpTrigger;
  46461. },
  46462. enumerable: true,
  46463. configurable: true
  46464. });
  46465. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  46466. /// This trigger will only be raised if you also declared a OnPickDown
  46467. get: function () {
  46468. return ActionManager._OnPickOutTrigger;
  46469. },
  46470. enumerable: true,
  46471. configurable: true
  46472. });
  46473. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  46474. get: function () {
  46475. return ActionManager._OnLongPressTrigger;
  46476. },
  46477. enumerable: true,
  46478. configurable: true
  46479. });
  46480. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  46481. get: function () {
  46482. return ActionManager._OnPointerOverTrigger;
  46483. },
  46484. enumerable: true,
  46485. configurable: true
  46486. });
  46487. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  46488. get: function () {
  46489. return ActionManager._OnPointerOutTrigger;
  46490. },
  46491. enumerable: true,
  46492. configurable: true
  46493. });
  46494. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  46495. get: function () {
  46496. return ActionManager._OnEveryFrameTrigger;
  46497. },
  46498. enumerable: true,
  46499. configurable: true
  46500. });
  46501. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  46502. get: function () {
  46503. return ActionManager._OnIntersectionEnterTrigger;
  46504. },
  46505. enumerable: true,
  46506. configurable: true
  46507. });
  46508. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  46509. get: function () {
  46510. return ActionManager._OnIntersectionExitTrigger;
  46511. },
  46512. enumerable: true,
  46513. configurable: true
  46514. });
  46515. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  46516. get: function () {
  46517. return ActionManager._OnKeyDownTrigger;
  46518. },
  46519. enumerable: true,
  46520. configurable: true
  46521. });
  46522. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  46523. get: function () {
  46524. return ActionManager._OnKeyUpTrigger;
  46525. },
  46526. enumerable: true,
  46527. configurable: true
  46528. });
  46529. // Methods
  46530. ActionManager.prototype.dispose = function () {
  46531. var index = this._scene._actionManagers.indexOf(this);
  46532. for (var i = 0; i < this.actions.length; i++) {
  46533. var action = this.actions[i];
  46534. ActionManager.Triggers[action.trigger]--;
  46535. if (ActionManager.Triggers[action.trigger] === 0) {
  46536. delete ActionManager.Triggers[action.trigger];
  46537. }
  46538. }
  46539. if (index > -1) {
  46540. this._scene._actionManagers.splice(index, 1);
  46541. }
  46542. };
  46543. ActionManager.prototype.getScene = function () {
  46544. return this._scene;
  46545. };
  46546. /**
  46547. * Does this action manager handles actions of any of the given triggers
  46548. * @param {number[]} triggers - the triggers to be tested
  46549. * @return {boolean} whether one (or more) of the triggers is handeled
  46550. */
  46551. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  46552. for (var index = 0; index < this.actions.length; index++) {
  46553. var action = this.actions[index];
  46554. if (triggers.indexOf(action.trigger) > -1) {
  46555. return true;
  46556. }
  46557. }
  46558. return false;
  46559. };
  46560. /**
  46561. * Does this action manager handles actions of a given trigger
  46562. * @param {number} trigger - the trigger to be tested
  46563. * @return {boolean} whether the trigger is handeled
  46564. */
  46565. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  46566. for (var index = 0; index < this.actions.length; index++) {
  46567. var action = this.actions[index];
  46568. if (action.trigger === trigger) {
  46569. return true;
  46570. }
  46571. }
  46572. return false;
  46573. };
  46574. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  46575. /**
  46576. * Does this action manager has pointer triggers
  46577. * @return {boolean} whether or not it has pointer triggers
  46578. */
  46579. get: function () {
  46580. for (var index = 0; index < this.actions.length; index++) {
  46581. var action = this.actions[index];
  46582. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  46583. return true;
  46584. }
  46585. }
  46586. return false;
  46587. },
  46588. enumerable: true,
  46589. configurable: true
  46590. });
  46591. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  46592. /**
  46593. * Does this action manager has pick triggers
  46594. * @return {boolean} whether or not it has pick triggers
  46595. */
  46596. get: function () {
  46597. for (var index = 0; index < this.actions.length; index++) {
  46598. var action = this.actions[index];
  46599. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  46600. return true;
  46601. }
  46602. }
  46603. return false;
  46604. },
  46605. enumerable: true,
  46606. configurable: true
  46607. });
  46608. Object.defineProperty(ActionManager, "HasTriggers", {
  46609. /**
  46610. * Does exist one action manager with at least one trigger
  46611. * @return {boolean} whether or not it exists one action manager with one trigger
  46612. **/
  46613. get: function () {
  46614. for (var t in ActionManager.Triggers) {
  46615. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46616. return true;
  46617. }
  46618. }
  46619. return false;
  46620. },
  46621. enumerable: true,
  46622. configurable: true
  46623. });
  46624. Object.defineProperty(ActionManager, "HasPickTriggers", {
  46625. /**
  46626. * Does exist one action manager with at least one pick trigger
  46627. * @return {boolean} whether or not it exists one action manager with one pick trigger
  46628. **/
  46629. get: function () {
  46630. for (var t in ActionManager.Triggers) {
  46631. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46632. var t_int = parseInt(t);
  46633. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  46634. return true;
  46635. }
  46636. }
  46637. }
  46638. return false;
  46639. },
  46640. enumerable: true,
  46641. configurable: true
  46642. });
  46643. /**
  46644. * Does exist one action manager that handles actions of a given trigger
  46645. * @param {number} trigger - the trigger to be tested
  46646. * @return {boolean} whether the trigger is handeled by at least one action manager
  46647. **/
  46648. ActionManager.HasSpecificTrigger = function (trigger) {
  46649. for (var t in ActionManager.Triggers) {
  46650. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46651. var t_int = parseInt(t);
  46652. if (t_int === trigger) {
  46653. return true;
  46654. }
  46655. }
  46656. }
  46657. return false;
  46658. };
  46659. /**
  46660. * Registers an action to this action manager
  46661. * @param {BABYLON.Action} action - the action to be registered
  46662. * @return {BABYLON.Action} the action amended (prepared) after registration
  46663. */
  46664. ActionManager.prototype.registerAction = function (action) {
  46665. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  46666. if (this.getScene().actionManager !== this) {
  46667. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  46668. return null;
  46669. }
  46670. }
  46671. this.actions.push(action);
  46672. if (ActionManager.Triggers[action.trigger]) {
  46673. ActionManager.Triggers[action.trigger]++;
  46674. }
  46675. else {
  46676. ActionManager.Triggers[action.trigger] = 1;
  46677. }
  46678. action._actionManager = this;
  46679. action._prepare();
  46680. return action;
  46681. };
  46682. /**
  46683. * Process a specific trigger
  46684. * @param {number} trigger - the trigger to process
  46685. * @param evt {BABYLON.ActionEvent} the event details to be processed
  46686. */
  46687. ActionManager.prototype.processTrigger = function (trigger, evt) {
  46688. for (var index = 0; index < this.actions.length; index++) {
  46689. var action = this.actions[index];
  46690. if (action.trigger === trigger) {
  46691. if (trigger === ActionManager.OnKeyUpTrigger
  46692. || trigger === ActionManager.OnKeyDownTrigger) {
  46693. var parameter = action.getTriggerParameter();
  46694. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  46695. if (!parameter.toLowerCase) {
  46696. continue;
  46697. }
  46698. var lowerCase = parameter.toLowerCase();
  46699. if (lowerCase !== evt.sourceEvent.key) {
  46700. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  46701. var actualkey = String.fromCharCode(unicode).toLowerCase();
  46702. if (actualkey !== lowerCase) {
  46703. continue;
  46704. }
  46705. }
  46706. }
  46707. }
  46708. action._executeCurrent(evt);
  46709. }
  46710. }
  46711. };
  46712. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  46713. var properties = propertyPath.split(".");
  46714. for (var index = 0; index < properties.length - 1; index++) {
  46715. target = target[properties[index]];
  46716. }
  46717. return target;
  46718. };
  46719. ActionManager.prototype._getProperty = function (propertyPath) {
  46720. var properties = propertyPath.split(".");
  46721. return properties[properties.length - 1];
  46722. };
  46723. ActionManager.prototype.serialize = function (name) {
  46724. var root = {
  46725. children: [],
  46726. name: name,
  46727. type: 3,
  46728. properties: [] // Empty for root but required
  46729. };
  46730. for (var i = 0; i < this.actions.length; i++) {
  46731. var triggerObject = {
  46732. type: 0,
  46733. children: [],
  46734. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  46735. properties: []
  46736. };
  46737. var triggerOptions = this.actions[i].triggerOptions;
  46738. if (triggerOptions && typeof triggerOptions !== "number") {
  46739. if (triggerOptions.parameter instanceof BABYLON.Node) {
  46740. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  46741. }
  46742. else {
  46743. var parameter = {};
  46744. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  46745. if (triggerOptions.parameter.mesh) {
  46746. parameter._meshId = triggerOptions.parameter.mesh.id;
  46747. }
  46748. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  46749. }
  46750. }
  46751. // Serialize child action, recursively
  46752. this.actions[i].serialize(triggerObject);
  46753. // Add serialized trigger
  46754. root.children.push(triggerObject);
  46755. }
  46756. return root;
  46757. };
  46758. ActionManager.Parse = function (parsedActions, object, scene) {
  46759. var actionManager = new BABYLON.ActionManager(scene);
  46760. if (object === null)
  46761. scene.actionManager = actionManager;
  46762. else
  46763. object.actionManager = actionManager;
  46764. // instanciate a new object
  46765. var instanciate = function (name, params) {
  46766. var newInstance = Object.create(BABYLON[name].prototype);
  46767. newInstance.constructor.apply(newInstance, params);
  46768. return newInstance;
  46769. };
  46770. var parseParameter = function (name, value, target, propertyPath) {
  46771. if (propertyPath === null) {
  46772. // String, boolean or float
  46773. var floatValue = parseFloat(value);
  46774. if (value === "true" || value === "false")
  46775. return value === "true";
  46776. else
  46777. return isNaN(floatValue) ? value : floatValue;
  46778. }
  46779. var effectiveTarget = propertyPath.split(".");
  46780. var values = value.split(",");
  46781. // Get effective Target
  46782. for (var i = 0; i < effectiveTarget.length; i++) {
  46783. target = target[effectiveTarget[i]];
  46784. }
  46785. // Return appropriate value with its type
  46786. if (typeof (target) === "boolean")
  46787. return values[0] === "true";
  46788. if (typeof (target) === "string")
  46789. return values[0];
  46790. // Parameters with multiple values such as Vector3 etc.
  46791. var split = new Array();
  46792. for (var i = 0; i < values.length; i++)
  46793. split.push(parseFloat(values[i]));
  46794. if (target instanceof BABYLON.Vector3)
  46795. return BABYLON.Vector3.FromArray(split);
  46796. if (target instanceof BABYLON.Vector4)
  46797. return BABYLON.Vector4.FromArray(split);
  46798. if (target instanceof BABYLON.Color3)
  46799. return BABYLON.Color3.FromArray(split);
  46800. if (target instanceof BABYLON.Color4)
  46801. return BABYLON.Color4.FromArray(split);
  46802. return parseFloat(values[0]);
  46803. };
  46804. // traverse graph per trigger
  46805. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  46806. if (combineArray === void 0) { combineArray = null; }
  46807. if (parsedAction.detached)
  46808. return;
  46809. var parameters = new Array();
  46810. var target = null;
  46811. var propertyPath = null;
  46812. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  46813. // Parameters
  46814. if (parsedAction.type === 2)
  46815. parameters.push(actionManager);
  46816. else
  46817. parameters.push(trigger);
  46818. if (combine) {
  46819. var actions = new Array();
  46820. for (var j = 0; j < parsedAction.combine.length; j++) {
  46821. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  46822. }
  46823. parameters.push(actions);
  46824. }
  46825. else {
  46826. for (var i = 0; i < parsedAction.properties.length; i++) {
  46827. var value = parsedAction.properties[i].value;
  46828. var name = parsedAction.properties[i].name;
  46829. var targetType = parsedAction.properties[i].targetType;
  46830. if (name === "target")
  46831. if (targetType !== null && targetType === "SceneProperties")
  46832. value = target = scene;
  46833. else
  46834. value = target = scene.getNodeByName(value);
  46835. else if (name === "parent")
  46836. value = scene.getNodeByName(value);
  46837. else if (name === "sound")
  46838. value = scene.getSoundByName(value);
  46839. else if (name !== "propertyPath") {
  46840. if (parsedAction.type === 2 && name === "operator")
  46841. value = BABYLON.ValueCondition[value];
  46842. else
  46843. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  46844. }
  46845. else {
  46846. propertyPath = value;
  46847. }
  46848. parameters.push(value);
  46849. }
  46850. }
  46851. if (combineArray === null) {
  46852. parameters.push(condition);
  46853. }
  46854. else {
  46855. parameters.push(null);
  46856. }
  46857. // If interpolate value action
  46858. if (parsedAction.name === "InterpolateValueAction") {
  46859. var param = parameters[parameters.length - 2];
  46860. parameters[parameters.length - 1] = param;
  46861. parameters[parameters.length - 2] = condition;
  46862. }
  46863. // Action or condition(s) and not CombineAction
  46864. var newAction = instanciate(parsedAction.name, parameters);
  46865. if (newAction instanceof BABYLON.Condition && condition !== null) {
  46866. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  46867. if (action)
  46868. action.then(nothing);
  46869. else
  46870. actionManager.registerAction(nothing);
  46871. action = nothing;
  46872. }
  46873. if (combineArray === null) {
  46874. if (newAction instanceof BABYLON.Condition) {
  46875. condition = newAction;
  46876. newAction = action;
  46877. }
  46878. else {
  46879. condition = null;
  46880. if (action)
  46881. action.then(newAction);
  46882. else
  46883. actionManager.registerAction(newAction);
  46884. }
  46885. }
  46886. else {
  46887. combineArray.push(newAction);
  46888. }
  46889. for (var i = 0; i < parsedAction.children.length; i++)
  46890. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  46891. };
  46892. // triggers
  46893. for (var i = 0; i < parsedActions.children.length; i++) {
  46894. var triggerParams;
  46895. var trigger = parsedActions.children[i];
  46896. if (trigger.properties.length > 0) {
  46897. var param = trigger.properties[0].value;
  46898. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  46899. if (value._meshId) {
  46900. value.mesh = scene.getMeshByID(value._meshId);
  46901. }
  46902. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  46903. }
  46904. else
  46905. triggerParams = BABYLON.ActionManager[trigger.name];
  46906. for (var j = 0; j < trigger.children.length; j++) {
  46907. if (!trigger.detached)
  46908. traverse(trigger.children[j], triggerParams, null, null);
  46909. }
  46910. }
  46911. };
  46912. ActionManager.GetTriggerName = function (trigger) {
  46913. switch (trigger) {
  46914. case 0: return "NothingTrigger";
  46915. case 1: return "OnPickTrigger";
  46916. case 2: return "OnLeftPickTrigger";
  46917. case 3: return "OnRightPickTrigger";
  46918. case 4: return "OnCenterPickTrigger";
  46919. case 5: return "OnPickDownTrigger";
  46920. case 6: return "OnPickUpTrigger";
  46921. case 7: return "OnLongPressTrigger";
  46922. case 8: return "OnPointerOverTrigger";
  46923. case 9: return "OnPointerOutTrigger";
  46924. case 10: return "OnEveryFrameTrigger";
  46925. case 11: return "OnIntersectionEnterTrigger";
  46926. case 12: return "OnIntersectionExitTrigger";
  46927. case 13: return "OnKeyDownTrigger";
  46928. case 14: return "OnKeyUpTrigger";
  46929. case 15: return "OnPickOutTrigger";
  46930. default: return "";
  46931. }
  46932. };
  46933. // Statics
  46934. ActionManager._NothingTrigger = 0;
  46935. ActionManager._OnPickTrigger = 1;
  46936. ActionManager._OnLeftPickTrigger = 2;
  46937. ActionManager._OnRightPickTrigger = 3;
  46938. ActionManager._OnCenterPickTrigger = 4;
  46939. ActionManager._OnPickDownTrigger = 5;
  46940. ActionManager._OnDoublePickTrigger = 6;
  46941. ActionManager._OnPickUpTrigger = 7;
  46942. ActionManager._OnLongPressTrigger = 8;
  46943. ActionManager._OnPointerOverTrigger = 9;
  46944. ActionManager._OnPointerOutTrigger = 10;
  46945. ActionManager._OnEveryFrameTrigger = 11;
  46946. ActionManager._OnIntersectionEnterTrigger = 12;
  46947. ActionManager._OnIntersectionExitTrigger = 13;
  46948. ActionManager._OnKeyDownTrigger = 14;
  46949. ActionManager._OnKeyUpTrigger = 15;
  46950. ActionManager._OnPickOutTrigger = 16;
  46951. ActionManager.Triggers = {};
  46952. return ActionManager;
  46953. }());
  46954. BABYLON.ActionManager = ActionManager;
  46955. })(BABYLON || (BABYLON = {}));
  46956. //# sourceMappingURL=babylon.actionManager.js.map
  46957. var BABYLON;
  46958. (function (BABYLON) {
  46959. var InterpolateValueAction = (function (_super) {
  46960. __extends(InterpolateValueAction, _super);
  46961. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  46962. if (duration === void 0) { duration = 1000; }
  46963. var _this = _super.call(this, triggerOptions, condition) || this;
  46964. _this.propertyPath = propertyPath;
  46965. _this.value = value;
  46966. _this.duration = duration;
  46967. _this.stopOtherAnimations = stopOtherAnimations;
  46968. _this.onInterpolationDone = onInterpolationDone;
  46969. _this._target = _this._effectiveTarget = target;
  46970. return _this;
  46971. }
  46972. InterpolateValueAction.prototype._prepare = function () {
  46973. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46974. this._property = this._getProperty(this.propertyPath);
  46975. };
  46976. InterpolateValueAction.prototype.execute = function () {
  46977. var scene = this._actionManager.getScene();
  46978. var keys = [
  46979. {
  46980. frame: 0,
  46981. value: this._effectiveTarget[this._property]
  46982. }, {
  46983. frame: 100,
  46984. value: this.value
  46985. }
  46986. ];
  46987. var dataType;
  46988. if (typeof this.value === "number") {
  46989. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  46990. }
  46991. else if (this.value instanceof BABYLON.Color3) {
  46992. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  46993. }
  46994. else if (this.value instanceof BABYLON.Vector3) {
  46995. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  46996. }
  46997. else if (this.value instanceof BABYLON.Matrix) {
  46998. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  46999. }
  47000. else if (this.value instanceof BABYLON.Quaternion) {
  47001. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  47002. }
  47003. else {
  47004. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  47005. return;
  47006. }
  47007. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  47008. animation.setKeys(keys);
  47009. if (this.stopOtherAnimations) {
  47010. scene.stopAnimation(this._effectiveTarget);
  47011. }
  47012. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  47013. };
  47014. InterpolateValueAction.prototype.serialize = function (parent) {
  47015. return _super.prototype._serialize.call(this, {
  47016. name: "InterpolateValueAction",
  47017. properties: [
  47018. BABYLON.Action._GetTargetProperty(this._target),
  47019. { name: "propertyPath", value: this.propertyPath },
  47020. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47021. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  47022. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  47023. ]
  47024. }, parent);
  47025. };
  47026. return InterpolateValueAction;
  47027. }(BABYLON.Action));
  47028. BABYLON.InterpolateValueAction = InterpolateValueAction;
  47029. })(BABYLON || (BABYLON = {}));
  47030. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  47031. var BABYLON;
  47032. (function (BABYLON) {
  47033. var SwitchBooleanAction = (function (_super) {
  47034. __extends(SwitchBooleanAction, _super);
  47035. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  47036. var _this = _super.call(this, triggerOptions, condition) || this;
  47037. _this.propertyPath = propertyPath;
  47038. _this._target = _this._effectiveTarget = target;
  47039. return _this;
  47040. }
  47041. SwitchBooleanAction.prototype._prepare = function () {
  47042. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47043. this._property = this._getProperty(this.propertyPath);
  47044. };
  47045. SwitchBooleanAction.prototype.execute = function () {
  47046. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  47047. };
  47048. SwitchBooleanAction.prototype.serialize = function (parent) {
  47049. return _super.prototype._serialize.call(this, {
  47050. name: "SwitchBooleanAction",
  47051. properties: [
  47052. BABYLON.Action._GetTargetProperty(this._target),
  47053. { name: "propertyPath", value: this.propertyPath }
  47054. ]
  47055. }, parent);
  47056. };
  47057. return SwitchBooleanAction;
  47058. }(BABYLON.Action));
  47059. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  47060. var SetStateAction = (function (_super) {
  47061. __extends(SetStateAction, _super);
  47062. function SetStateAction(triggerOptions, target, value, condition) {
  47063. var _this = _super.call(this, triggerOptions, condition) || this;
  47064. _this.value = value;
  47065. _this._target = target;
  47066. return _this;
  47067. }
  47068. SetStateAction.prototype.execute = function () {
  47069. this._target.state = this.value;
  47070. };
  47071. SetStateAction.prototype.serialize = function (parent) {
  47072. return _super.prototype._serialize.call(this, {
  47073. name: "SetStateAction",
  47074. properties: [
  47075. BABYLON.Action._GetTargetProperty(this._target),
  47076. { name: "value", value: this.value }
  47077. ]
  47078. }, parent);
  47079. };
  47080. return SetStateAction;
  47081. }(BABYLON.Action));
  47082. BABYLON.SetStateAction = SetStateAction;
  47083. var SetValueAction = (function (_super) {
  47084. __extends(SetValueAction, _super);
  47085. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  47086. var _this = _super.call(this, triggerOptions, condition) || this;
  47087. _this.propertyPath = propertyPath;
  47088. _this.value = value;
  47089. _this._target = _this._effectiveTarget = target;
  47090. return _this;
  47091. }
  47092. SetValueAction.prototype._prepare = function () {
  47093. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47094. this._property = this._getProperty(this.propertyPath);
  47095. };
  47096. SetValueAction.prototype.execute = function () {
  47097. this._effectiveTarget[this._property] = this.value;
  47098. if (this._target.markAsDirty) {
  47099. this._target.markAsDirty(this._property);
  47100. }
  47101. };
  47102. SetValueAction.prototype.serialize = function (parent) {
  47103. return _super.prototype._serialize.call(this, {
  47104. name: "SetValueAction",
  47105. properties: [
  47106. BABYLON.Action._GetTargetProperty(this._target),
  47107. { name: "propertyPath", value: this.propertyPath },
  47108. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  47109. ]
  47110. }, parent);
  47111. };
  47112. return SetValueAction;
  47113. }(BABYLON.Action));
  47114. BABYLON.SetValueAction = SetValueAction;
  47115. var IncrementValueAction = (function (_super) {
  47116. __extends(IncrementValueAction, _super);
  47117. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  47118. var _this = _super.call(this, triggerOptions, condition) || this;
  47119. _this.propertyPath = propertyPath;
  47120. _this.value = value;
  47121. _this._target = _this._effectiveTarget = target;
  47122. return _this;
  47123. }
  47124. IncrementValueAction.prototype._prepare = function () {
  47125. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47126. this._property = this._getProperty(this.propertyPath);
  47127. if (typeof this._effectiveTarget[this._property] !== "number") {
  47128. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  47129. }
  47130. };
  47131. IncrementValueAction.prototype.execute = function () {
  47132. this._effectiveTarget[this._property] += this.value;
  47133. if (this._target.markAsDirty) {
  47134. this._target.markAsDirty(this._property);
  47135. }
  47136. };
  47137. IncrementValueAction.prototype.serialize = function (parent) {
  47138. return _super.prototype._serialize.call(this, {
  47139. name: "IncrementValueAction",
  47140. properties: [
  47141. BABYLON.Action._GetTargetProperty(this._target),
  47142. { name: "propertyPath", value: this.propertyPath },
  47143. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  47144. ]
  47145. }, parent);
  47146. };
  47147. return IncrementValueAction;
  47148. }(BABYLON.Action));
  47149. BABYLON.IncrementValueAction = IncrementValueAction;
  47150. var PlayAnimationAction = (function (_super) {
  47151. __extends(PlayAnimationAction, _super);
  47152. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  47153. var _this = _super.call(this, triggerOptions, condition) || this;
  47154. _this.from = from;
  47155. _this.to = to;
  47156. _this.loop = loop;
  47157. _this._target = target;
  47158. return _this;
  47159. }
  47160. PlayAnimationAction.prototype._prepare = function () {
  47161. };
  47162. PlayAnimationAction.prototype.execute = function () {
  47163. var scene = this._actionManager.getScene();
  47164. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  47165. };
  47166. PlayAnimationAction.prototype.serialize = function (parent) {
  47167. return _super.prototype._serialize.call(this, {
  47168. name: "PlayAnimationAction",
  47169. properties: [
  47170. BABYLON.Action._GetTargetProperty(this._target),
  47171. { name: "from", value: String(this.from) },
  47172. { name: "to", value: String(this.to) },
  47173. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  47174. ]
  47175. }, parent);
  47176. };
  47177. return PlayAnimationAction;
  47178. }(BABYLON.Action));
  47179. BABYLON.PlayAnimationAction = PlayAnimationAction;
  47180. var StopAnimationAction = (function (_super) {
  47181. __extends(StopAnimationAction, _super);
  47182. function StopAnimationAction(triggerOptions, target, condition) {
  47183. var _this = _super.call(this, triggerOptions, condition) || this;
  47184. _this._target = target;
  47185. return _this;
  47186. }
  47187. StopAnimationAction.prototype._prepare = function () {
  47188. };
  47189. StopAnimationAction.prototype.execute = function () {
  47190. var scene = this._actionManager.getScene();
  47191. scene.stopAnimation(this._target);
  47192. };
  47193. StopAnimationAction.prototype.serialize = function (parent) {
  47194. return _super.prototype._serialize.call(this, {
  47195. name: "StopAnimationAction",
  47196. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  47197. }, parent);
  47198. };
  47199. return StopAnimationAction;
  47200. }(BABYLON.Action));
  47201. BABYLON.StopAnimationAction = StopAnimationAction;
  47202. var DoNothingAction = (function (_super) {
  47203. __extends(DoNothingAction, _super);
  47204. function DoNothingAction(triggerOptions, condition) {
  47205. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  47206. return _super.call(this, triggerOptions, condition) || this;
  47207. }
  47208. DoNothingAction.prototype.execute = function () {
  47209. };
  47210. DoNothingAction.prototype.serialize = function (parent) {
  47211. return _super.prototype._serialize.call(this, {
  47212. name: "DoNothingAction",
  47213. properties: []
  47214. }, parent);
  47215. };
  47216. return DoNothingAction;
  47217. }(BABYLON.Action));
  47218. BABYLON.DoNothingAction = DoNothingAction;
  47219. var CombineAction = (function (_super) {
  47220. __extends(CombineAction, _super);
  47221. function CombineAction(triggerOptions, children, condition) {
  47222. var _this = _super.call(this, triggerOptions, condition) || this;
  47223. _this.children = children;
  47224. return _this;
  47225. }
  47226. CombineAction.prototype._prepare = function () {
  47227. for (var index = 0; index < this.children.length; index++) {
  47228. this.children[index]._actionManager = this._actionManager;
  47229. this.children[index]._prepare();
  47230. }
  47231. };
  47232. CombineAction.prototype.execute = function (evt) {
  47233. for (var index = 0; index < this.children.length; index++) {
  47234. this.children[index].execute(evt);
  47235. }
  47236. };
  47237. CombineAction.prototype.serialize = function (parent) {
  47238. var serializationObject = _super.prototype._serialize.call(this, {
  47239. name: "CombineAction",
  47240. properties: [],
  47241. combine: []
  47242. }, parent);
  47243. for (var i = 0; i < this.children.length; i++) {
  47244. serializationObject.combine.push(this.children[i].serialize(null));
  47245. }
  47246. return serializationObject;
  47247. };
  47248. return CombineAction;
  47249. }(BABYLON.Action));
  47250. BABYLON.CombineAction = CombineAction;
  47251. var ExecuteCodeAction = (function (_super) {
  47252. __extends(ExecuteCodeAction, _super);
  47253. function ExecuteCodeAction(triggerOptions, func, condition) {
  47254. var _this = _super.call(this, triggerOptions, condition) || this;
  47255. _this.func = func;
  47256. return _this;
  47257. }
  47258. ExecuteCodeAction.prototype.execute = function (evt) {
  47259. this.func(evt);
  47260. };
  47261. return ExecuteCodeAction;
  47262. }(BABYLON.Action));
  47263. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  47264. var SetParentAction = (function (_super) {
  47265. __extends(SetParentAction, _super);
  47266. function SetParentAction(triggerOptions, target, parent, condition) {
  47267. var _this = _super.call(this, triggerOptions, condition) || this;
  47268. _this._target = target;
  47269. _this._parent = parent;
  47270. return _this;
  47271. }
  47272. SetParentAction.prototype._prepare = function () {
  47273. };
  47274. SetParentAction.prototype.execute = function () {
  47275. if (this._target.parent === this._parent) {
  47276. return;
  47277. }
  47278. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  47279. invertParentWorldMatrix.invert();
  47280. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  47281. this._target.parent = this._parent;
  47282. };
  47283. SetParentAction.prototype.serialize = function (parent) {
  47284. return _super.prototype._serialize.call(this, {
  47285. name: "SetParentAction",
  47286. properties: [
  47287. BABYLON.Action._GetTargetProperty(this._target),
  47288. BABYLON.Action._GetTargetProperty(this._parent),
  47289. ]
  47290. }, parent);
  47291. };
  47292. return SetParentAction;
  47293. }(BABYLON.Action));
  47294. BABYLON.SetParentAction = SetParentAction;
  47295. var PlaySoundAction = (function (_super) {
  47296. __extends(PlaySoundAction, _super);
  47297. function PlaySoundAction(triggerOptions, sound, condition) {
  47298. var _this = _super.call(this, triggerOptions, condition) || this;
  47299. _this._sound = sound;
  47300. return _this;
  47301. }
  47302. PlaySoundAction.prototype._prepare = function () {
  47303. };
  47304. PlaySoundAction.prototype.execute = function () {
  47305. if (this._sound !== undefined)
  47306. this._sound.play();
  47307. };
  47308. PlaySoundAction.prototype.serialize = function (parent) {
  47309. return _super.prototype._serialize.call(this, {
  47310. name: "PlaySoundAction",
  47311. properties: [{ name: "sound", value: this._sound.name }]
  47312. }, parent);
  47313. };
  47314. return PlaySoundAction;
  47315. }(BABYLON.Action));
  47316. BABYLON.PlaySoundAction = PlaySoundAction;
  47317. var StopSoundAction = (function (_super) {
  47318. __extends(StopSoundAction, _super);
  47319. function StopSoundAction(triggerOptions, sound, condition) {
  47320. var _this = _super.call(this, triggerOptions, condition) || this;
  47321. _this._sound = sound;
  47322. return _this;
  47323. }
  47324. StopSoundAction.prototype._prepare = function () {
  47325. };
  47326. StopSoundAction.prototype.execute = function () {
  47327. if (this._sound !== undefined)
  47328. this._sound.stop();
  47329. };
  47330. StopSoundAction.prototype.serialize = function (parent) {
  47331. return _super.prototype._serialize.call(this, {
  47332. name: "StopSoundAction",
  47333. properties: [{ name: "sound", value: this._sound.name }]
  47334. }, parent);
  47335. };
  47336. return StopSoundAction;
  47337. }(BABYLON.Action));
  47338. BABYLON.StopSoundAction = StopSoundAction;
  47339. })(BABYLON || (BABYLON = {}));
  47340. //# sourceMappingURL=babylon.directActions.js.map
  47341. var BABYLON;
  47342. (function (BABYLON) {
  47343. var Debug;
  47344. (function (Debug) {
  47345. /**
  47346. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  47347. */
  47348. var SkeletonViewer = (function () {
  47349. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  47350. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  47351. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  47352. this.skeleton = skeleton;
  47353. this.mesh = mesh;
  47354. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  47355. this.renderingGroupId = renderingGroupId;
  47356. this.color = BABYLON.Color3.White();
  47357. this._debugLines = [];
  47358. this._isEnabled = false;
  47359. this._scene = scene;
  47360. this.update();
  47361. this._renderFunction = this.update.bind(this);
  47362. }
  47363. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  47364. get: function () {
  47365. return this._isEnabled;
  47366. },
  47367. set: function (value) {
  47368. if (this._isEnabled === value) {
  47369. return;
  47370. }
  47371. this._isEnabled = value;
  47372. if (value) {
  47373. this._scene.registerBeforeRender(this._renderFunction);
  47374. }
  47375. else {
  47376. this._scene.unregisterBeforeRender(this._renderFunction);
  47377. }
  47378. },
  47379. enumerable: true,
  47380. configurable: true
  47381. });
  47382. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  47383. if (x === void 0) { x = 0; }
  47384. if (y === void 0) { y = 0; }
  47385. if (z === void 0) { z = 0; }
  47386. var tmat = BABYLON.Tmp.Matrix[0];
  47387. var parentBone = bone.getParent();
  47388. tmat.copyFrom(bone.getLocalMatrix());
  47389. if (x !== 0 || y !== 0 || z !== 0) {
  47390. var tmat2 = BABYLON.Tmp.Matrix[1];
  47391. BABYLON.Matrix.IdentityToRef(tmat2);
  47392. tmat2.m[12] = x;
  47393. tmat2.m[13] = y;
  47394. tmat2.m[14] = z;
  47395. tmat2.multiplyToRef(tmat, tmat);
  47396. }
  47397. if (parentBone) {
  47398. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  47399. }
  47400. tmat.multiplyToRef(meshMat, tmat);
  47401. position.x = tmat.m[12];
  47402. position.y = tmat.m[13];
  47403. position.z = tmat.m[14];
  47404. };
  47405. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  47406. var len = bones.length;
  47407. var meshPos = this.mesh.position;
  47408. for (var i = 0; i < len; i++) {
  47409. var bone = bones[i];
  47410. var points = this._debugLines[i];
  47411. if (!points) {
  47412. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47413. this._debugLines[i] = points;
  47414. }
  47415. this._getBonePosition(points[0], bone, meshMat);
  47416. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  47417. points[0].subtractInPlace(meshPos);
  47418. points[1].subtractInPlace(meshPos);
  47419. }
  47420. };
  47421. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  47422. var len = bones.length;
  47423. var boneNum = 0;
  47424. var meshPos = this.mesh.position;
  47425. for (var i = len - 1; i >= 0; i--) {
  47426. var childBone = bones[i];
  47427. var parentBone = childBone.getParent();
  47428. if (!parentBone) {
  47429. continue;
  47430. }
  47431. var points = this._debugLines[boneNum];
  47432. if (!points) {
  47433. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47434. this._debugLines[boneNum] = points;
  47435. }
  47436. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  47437. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  47438. points[0].subtractInPlace(meshPos);
  47439. points[1].subtractInPlace(meshPos);
  47440. boneNum++;
  47441. }
  47442. };
  47443. SkeletonViewer.prototype.update = function () {
  47444. if (this.autoUpdateBonesMatrices) {
  47445. this.skeleton.computeAbsoluteTransforms();
  47446. }
  47447. if (this.skeleton.bones[0].length === undefined) {
  47448. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  47449. }
  47450. else {
  47451. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  47452. }
  47453. if (!this._debugMesh) {
  47454. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  47455. this._debugMesh.renderingGroupId = this.renderingGroupId;
  47456. }
  47457. else {
  47458. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  47459. }
  47460. this._debugMesh.position.copyFrom(this.mesh.position);
  47461. this._debugMesh.color = this.color;
  47462. };
  47463. SkeletonViewer.prototype.dispose = function () {
  47464. if (this._debugMesh) {
  47465. this.isEnabled = false;
  47466. this._debugMesh.dispose();
  47467. this._debugMesh = null;
  47468. }
  47469. };
  47470. return SkeletonViewer;
  47471. }());
  47472. Debug.SkeletonViewer = SkeletonViewer;
  47473. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47474. })(BABYLON || (BABYLON = {}));
  47475. //# sourceMappingURL=babylon.skeletonViewer.js.map
  47476. var BABYLON;
  47477. (function (BABYLON) {
  47478. var Debug;
  47479. (function (Debug) {
  47480. var AxesViewer = (function () {
  47481. function AxesViewer(scene, scaleLines) {
  47482. if (scaleLines === void 0) { scaleLines = 1; }
  47483. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47484. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47485. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  47486. this.scaleLines = 1;
  47487. this.scaleLines = scaleLines;
  47488. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  47489. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  47490. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  47491. this._xmesh.renderingGroupId = 2;
  47492. this._ymesh.renderingGroupId = 2;
  47493. this._zmesh.renderingGroupId = 2;
  47494. this._xmesh.material.checkReadyOnlyOnce = true;
  47495. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  47496. this._ymesh.material.checkReadyOnlyOnce = true;
  47497. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  47498. this._zmesh.material.checkReadyOnlyOnce = true;
  47499. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  47500. this.scene = scene;
  47501. }
  47502. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  47503. var scaleLines = this.scaleLines;
  47504. this._xmesh.position.copyFrom(position);
  47505. this._ymesh.position.copyFrom(position);
  47506. this._zmesh.position.copyFrom(position);
  47507. var point2 = this._xline[1];
  47508. point2.x = xaxis.x * scaleLines;
  47509. point2.y = xaxis.y * scaleLines;
  47510. point2.z = xaxis.z * scaleLines;
  47511. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  47512. point2 = this._yline[1];
  47513. point2.x = yaxis.x * scaleLines;
  47514. point2.y = yaxis.y * scaleLines;
  47515. point2.z = yaxis.z * scaleLines;
  47516. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  47517. point2 = this._zline[1];
  47518. point2.x = zaxis.x * scaleLines;
  47519. point2.y = zaxis.y * scaleLines;
  47520. point2.z = zaxis.z * scaleLines;
  47521. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  47522. };
  47523. AxesViewer.prototype.dispose = function () {
  47524. if (this._xmesh) {
  47525. this._xmesh.dispose();
  47526. this._ymesh.dispose();
  47527. this._zmesh.dispose();
  47528. this._xmesh = null;
  47529. this._ymesh = null;
  47530. this._zmesh = null;
  47531. this._xline = null;
  47532. this._yline = null;
  47533. this._zline = null;
  47534. this.scene = null;
  47535. }
  47536. };
  47537. return AxesViewer;
  47538. }());
  47539. Debug.AxesViewer = AxesViewer;
  47540. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47541. })(BABYLON || (BABYLON = {}));
  47542. //# sourceMappingURL=babylon.axesViewer.js.map
  47543. var BABYLON;
  47544. (function (BABYLON) {
  47545. var Debug;
  47546. (function (Debug) {
  47547. var BoneAxesViewer = (function (_super) {
  47548. __extends(BoneAxesViewer, _super);
  47549. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  47550. if (scaleLines === void 0) { scaleLines = 1; }
  47551. var _this = _super.call(this, scene, scaleLines) || this;
  47552. _this.pos = BABYLON.Vector3.Zero();
  47553. _this.xaxis = BABYLON.Vector3.Zero();
  47554. _this.yaxis = BABYLON.Vector3.Zero();
  47555. _this.zaxis = BABYLON.Vector3.Zero();
  47556. _this.mesh = mesh;
  47557. _this.bone = bone;
  47558. return _this;
  47559. }
  47560. BoneAxesViewer.prototype.update = function () {
  47561. var bone = this.bone;
  47562. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  47563. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  47564. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  47565. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  47566. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  47567. };
  47568. BoneAxesViewer.prototype.dispose = function () {
  47569. if (this.pos) {
  47570. this.pos = null;
  47571. this.xaxis = null;
  47572. this.yaxis = null;
  47573. this.zaxis = null;
  47574. this.mesh = null;
  47575. this.bone = null;
  47576. _super.prototype.dispose.call(this);
  47577. }
  47578. };
  47579. return BoneAxesViewer;
  47580. }(Debug.AxesViewer));
  47581. Debug.BoneAxesViewer = BoneAxesViewer;
  47582. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47583. })(BABYLON || (BABYLON = {}));
  47584. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  47585. var BABYLON;
  47586. (function (BABYLON) {
  47587. var RayHelper = (function () {
  47588. function RayHelper(ray) {
  47589. this.ray = ray;
  47590. }
  47591. RayHelper.CreateAndShow = function (ray, scene, color) {
  47592. var helper = new RayHelper(ray);
  47593. helper.show(scene, color);
  47594. return helper;
  47595. };
  47596. RayHelper.prototype.show = function (scene, color) {
  47597. if (!this._renderFunction) {
  47598. var ray = this.ray;
  47599. this._renderFunction = this._render.bind(this);
  47600. this._scene = scene;
  47601. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  47602. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  47603. this._scene.registerBeforeRender(this._renderFunction);
  47604. }
  47605. if (color) {
  47606. this._renderLine.color.copyFrom(color);
  47607. }
  47608. };
  47609. RayHelper.prototype.hide = function () {
  47610. if (this._renderFunction) {
  47611. this._scene.unregisterBeforeRender(this._renderFunction);
  47612. this._scene = null;
  47613. this._renderFunction = null;
  47614. this._renderLine.dispose();
  47615. this._renderLine = null;
  47616. this._renderPoints = null;
  47617. }
  47618. };
  47619. RayHelper.prototype._render = function () {
  47620. var ray = this.ray;
  47621. var point = this._renderPoints[1];
  47622. var len = Math.min(ray.length, 1000000);
  47623. point.copyFrom(ray.direction);
  47624. point.scaleInPlace(len);
  47625. point.addInPlace(ray.origin);
  47626. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  47627. };
  47628. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  47629. this._attachedToMesh = mesh;
  47630. var ray = this.ray;
  47631. if (!ray.direction) {
  47632. ray.direction = BABYLON.Vector3.Zero();
  47633. }
  47634. if (!ray.origin) {
  47635. ray.origin = BABYLON.Vector3.Zero();
  47636. }
  47637. if (length) {
  47638. ray.length = length;
  47639. }
  47640. if (!meshSpaceOrigin) {
  47641. meshSpaceOrigin = BABYLON.Vector3.Zero();
  47642. }
  47643. if (!meshSpaceDirection) {
  47644. // -1 so that this will work with Mesh.lookAt
  47645. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  47646. }
  47647. if (!this._meshSpaceDirection) {
  47648. this._meshSpaceDirection = meshSpaceDirection.clone();
  47649. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  47650. }
  47651. else {
  47652. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  47653. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  47654. }
  47655. if (!this._updateToMeshFunction) {
  47656. this._updateToMeshFunction = this._updateToMesh.bind(this);
  47657. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  47658. }
  47659. this._updateToMesh();
  47660. };
  47661. RayHelper.prototype.detachFromMesh = function () {
  47662. if (this._attachedToMesh) {
  47663. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  47664. this._attachedToMesh = null;
  47665. this._updateToMeshFunction = null;
  47666. }
  47667. };
  47668. RayHelper.prototype._updateToMesh = function () {
  47669. var ray = this.ray;
  47670. if (this._attachedToMesh._isDisposed) {
  47671. this.detachFromMesh();
  47672. return;
  47673. }
  47674. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  47675. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  47676. };
  47677. RayHelper.prototype.dispose = function () {
  47678. this.hide();
  47679. this.detachFromMesh();
  47680. this.ray = null;
  47681. };
  47682. return RayHelper;
  47683. }());
  47684. BABYLON.RayHelper = RayHelper;
  47685. })(BABYLON || (BABYLON = {}));
  47686. //# sourceMappingURL=babylon.rayHelper.js.map
  47687. var BABYLON;
  47688. (function (BABYLON) {
  47689. var DebugLayer = (function () {
  47690. function DebugLayer(scene) {
  47691. this._scene = scene;
  47692. }
  47693. /** Creates the inspector window. */
  47694. DebugLayer.prototype._createInspector = function (config) {
  47695. if (config === void 0) { config = {}; }
  47696. var popup = config.popup || false;
  47697. var initialTab = config.initialTab || 0;
  47698. var parentElement = config.parentElement || null;
  47699. if (!this._inspector) {
  47700. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  47701. } // else nothing to do,; instance is already existing
  47702. };
  47703. DebugLayer.prototype.isVisible = function () {
  47704. if (!this._inspector) {
  47705. return false;
  47706. }
  47707. return true;
  47708. };
  47709. DebugLayer.prototype.hide = function () {
  47710. if (this._inspector) {
  47711. try {
  47712. this._inspector.dispose();
  47713. }
  47714. catch (e) {
  47715. // If the inspector has been removed directly from the inspector tool
  47716. }
  47717. this._inspector = null;
  47718. }
  47719. };
  47720. DebugLayer.prototype.show = function (config) {
  47721. if (config === void 0) { config = {}; }
  47722. if (typeof INSPECTOR == 'undefined') {
  47723. // Load inspector and add it to the DOM
  47724. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  47725. }
  47726. else {
  47727. // Otherwise creates the inspector
  47728. this._createInspector(config);
  47729. }
  47730. };
  47731. // Get protocol used - http or https
  47732. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  47733. return DebugLayer;
  47734. }());
  47735. BABYLON.DebugLayer = DebugLayer;
  47736. })(BABYLON || (BABYLON = {}));
  47737. //# sourceMappingURL=babylon.debugLayer.js.map
  47738. var BABYLON;
  47739. (function (BABYLON) {
  47740. var Debug;
  47741. (function (Debug) {
  47742. var PhysicsViewer = (function () {
  47743. function PhysicsViewer(scene) {
  47744. this._impostors = [];
  47745. this._meshes = [];
  47746. this._numMeshes = 0;
  47747. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47748. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  47749. }
  47750. PhysicsViewer.prototype._updateDebugMeshes = function () {
  47751. var plugin = this._physicsEnginePlugin;
  47752. for (var i = 0; i < this._numMeshes; i++) {
  47753. if (this._impostors[i].isDisposed) {
  47754. this.hideImpostor(this._impostors[i--]);
  47755. }
  47756. else {
  47757. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  47758. }
  47759. }
  47760. };
  47761. PhysicsViewer.prototype.showImpostor = function (impostor) {
  47762. for (var i = 0; i < this._numMeshes; i++) {
  47763. if (this._impostors[i] == impostor) {
  47764. return;
  47765. }
  47766. }
  47767. var debugMesh = this._getDebugMesh(impostor, this._scene);
  47768. if (debugMesh) {
  47769. this._impostors[this._numMeshes] = impostor;
  47770. this._meshes[this._numMeshes] = debugMesh;
  47771. if (this._numMeshes === 0) {
  47772. this._renderFunction = this._updateDebugMeshes.bind(this);
  47773. this._scene.registerBeforeRender(this._renderFunction);
  47774. }
  47775. this._numMeshes++;
  47776. }
  47777. };
  47778. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  47779. var removed = false;
  47780. for (var i = 0; i < this._numMeshes; i++) {
  47781. if (this._impostors[i] == impostor) {
  47782. this._scene.removeMesh(this._meshes[i]);
  47783. this._meshes[i].dispose();
  47784. this._numMeshes--;
  47785. if (this._numMeshes > 0) {
  47786. this._meshes[i] = this._meshes[this._numMeshes];
  47787. this._impostors[i] = this._impostors[this._numMeshes];
  47788. this._meshes[this._numMeshes] = null;
  47789. this._impostors[this._numMeshes] = null;
  47790. }
  47791. else {
  47792. this._meshes[0] = null;
  47793. this._impostors[0] = null;
  47794. }
  47795. removed = true;
  47796. break;
  47797. }
  47798. }
  47799. if (removed && this._numMeshes === 0) {
  47800. this._scene.unregisterBeforeRender(this._renderFunction);
  47801. }
  47802. };
  47803. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  47804. if (!this._debugMaterial) {
  47805. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  47806. this._debugMaterial.wireframe = true;
  47807. }
  47808. return this._debugMaterial;
  47809. };
  47810. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  47811. if (!this._debugBoxMesh) {
  47812. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  47813. this._debugBoxMesh.renderingGroupId = 1;
  47814. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  47815. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  47816. scene.removeMesh(this._debugBoxMesh);
  47817. }
  47818. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  47819. };
  47820. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  47821. if (!this._debugSphereMesh) {
  47822. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  47823. this._debugSphereMesh.renderingGroupId = 1;
  47824. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  47825. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  47826. scene.removeMesh(this._debugSphereMesh);
  47827. }
  47828. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  47829. };
  47830. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  47831. var body = impostor.physicsBody;
  47832. var shape = body.shapes[0];
  47833. var mesh;
  47834. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  47835. mesh = this._getDebugBoxMesh(scene);
  47836. impostor.getBoxSizeToRef(mesh.scaling);
  47837. }
  47838. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  47839. mesh = this._getDebugSphereMesh(scene);
  47840. var radius = impostor.getRadius();
  47841. mesh.scaling.x = radius * 2;
  47842. mesh.scaling.y = radius * 2;
  47843. mesh.scaling.z = radius * 2;
  47844. }
  47845. return mesh;
  47846. };
  47847. PhysicsViewer.prototype.dispose = function () {
  47848. for (var i = 0; i < this._numMeshes; i++) {
  47849. this.hideImpostor(this._impostors[i]);
  47850. }
  47851. if (this._debugBoxMesh) {
  47852. this._debugBoxMesh.dispose();
  47853. }
  47854. if (this._debugSphereMesh) {
  47855. this._debugSphereMesh.dispose();
  47856. }
  47857. if (this._debugMaterial) {
  47858. this._debugMaterial.dispose();
  47859. }
  47860. this._impostors.length = 0;
  47861. this._scene = null;
  47862. this._physicsEnginePlugin = null;
  47863. };
  47864. return PhysicsViewer;
  47865. }());
  47866. Debug.PhysicsViewer = PhysicsViewer;
  47867. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  47868. })(BABYLON || (BABYLON = {}));
  47869. //# sourceMappingURL=babylon.physicsViewer.js.map
  47870. var BABYLON;
  47871. (function (BABYLON) {
  47872. var BoundingBoxRenderer = (function () {
  47873. function BoundingBoxRenderer(scene) {
  47874. this.frontColor = new BABYLON.Color3(1, 1, 1);
  47875. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  47876. this.showBackLines = true;
  47877. this.renderList = new BABYLON.SmartArray(32);
  47878. this._vertexBuffers = {};
  47879. this._scene = scene;
  47880. }
  47881. BoundingBoxRenderer.prototype._prepareRessources = function () {
  47882. if (this._colorShader) {
  47883. return;
  47884. }
  47885. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  47886. attributes: [BABYLON.VertexBuffer.PositionKind],
  47887. uniforms: ["world", "viewProjection", "color"]
  47888. });
  47889. var engine = this._scene.getEngine();
  47890. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  47891. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  47892. this._createIndexBuffer();
  47893. };
  47894. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  47895. var engine = this._scene.getEngine();
  47896. 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]);
  47897. };
  47898. BoundingBoxRenderer.prototype._rebuild = function () {
  47899. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  47900. this._createIndexBuffer();
  47901. };
  47902. BoundingBoxRenderer.prototype.reset = function () {
  47903. this.renderList.reset();
  47904. };
  47905. BoundingBoxRenderer.prototype.render = function () {
  47906. if (this.renderList.length === 0) {
  47907. return;
  47908. }
  47909. this._prepareRessources();
  47910. if (!this._colorShader.isReady()) {
  47911. return;
  47912. }
  47913. var engine = this._scene.getEngine();
  47914. engine.setDepthWrite(false);
  47915. this._colorShader._preBind();
  47916. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  47917. var boundingBox = this.renderList.data[boundingBoxIndex];
  47918. var min = boundingBox.minimum;
  47919. var max = boundingBox.maximum;
  47920. var diff = max.subtract(min);
  47921. var median = min.add(diff.scale(0.5));
  47922. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  47923. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  47924. .multiply(boundingBox.getWorldMatrix());
  47925. // VBOs
  47926. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  47927. if (this.showBackLines) {
  47928. // Back
  47929. engine.setDepthFunctionToGreaterOrEqual();
  47930. this._scene.resetCachedMaterial();
  47931. this._colorShader.setColor4("color", this.backColor.toColor4());
  47932. this._colorShader.bind(worldMatrix);
  47933. // Draw order
  47934. engine.draw(false, 0, 24);
  47935. }
  47936. // Front
  47937. engine.setDepthFunctionToLess();
  47938. this._scene.resetCachedMaterial();
  47939. this._colorShader.setColor4("color", this.frontColor.toColor4());
  47940. this._colorShader.bind(worldMatrix);
  47941. // Draw order
  47942. engine.draw(false, 0, 24);
  47943. }
  47944. this._colorShader.unbind();
  47945. engine.setDepthFunctionToLessOrEqual();
  47946. engine.setDepthWrite(true);
  47947. };
  47948. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  47949. this._prepareRessources();
  47950. if (!this._colorShader.isReady()) {
  47951. return;
  47952. }
  47953. var engine = this._scene.getEngine();
  47954. engine.setDepthWrite(false);
  47955. engine.setColorWrite(false);
  47956. this._colorShader._preBind();
  47957. var boundingBox = mesh._boundingInfo.boundingBox;
  47958. var min = boundingBox.minimum;
  47959. var max = boundingBox.maximum;
  47960. var diff = max.subtract(min);
  47961. var median = min.add(diff.scale(0.5));
  47962. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  47963. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  47964. .multiply(boundingBox.getWorldMatrix());
  47965. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  47966. engine.setDepthFunctionToLess();
  47967. this._scene.resetCachedMaterial();
  47968. this._colorShader.bind(worldMatrix);
  47969. engine.draw(false, 0, 24);
  47970. this._colorShader.unbind();
  47971. engine.setDepthFunctionToLessOrEqual();
  47972. engine.setDepthWrite(true);
  47973. engine.setColorWrite(true);
  47974. };
  47975. BoundingBoxRenderer.prototype.dispose = function () {
  47976. if (!this._colorShader) {
  47977. return;
  47978. }
  47979. this.renderList.dispose();
  47980. this._colorShader.dispose();
  47981. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  47982. if (buffer) {
  47983. buffer.dispose();
  47984. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  47985. }
  47986. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47987. };
  47988. return BoundingBoxRenderer;
  47989. }());
  47990. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  47991. })(BABYLON || (BABYLON = {}));
  47992. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  47993. var BABYLON;
  47994. (function (BABYLON) {
  47995. var TextureTools = (function () {
  47996. function TextureTools() {
  47997. }
  47998. /**
  47999. * Uses the GPU to create a copy texture rescaled at a given size
  48000. * @param texture Texture to copy from
  48001. * @param width Desired width
  48002. * @param height Desired height
  48003. * @return Generated texture
  48004. */
  48005. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  48006. if (useBilinearMode === void 0) { useBilinearMode = true; }
  48007. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  48008. var scene = texture.getScene();
  48009. var engine = scene.getEngine();
  48010. rtt.wrapU = texture.wrapU;
  48011. rtt.wrapV = texture.wrapV;
  48012. rtt.uOffset = texture.uOffset;
  48013. rtt.vOffset = texture.vOffset;
  48014. rtt.uScale = texture.uScale;
  48015. rtt.vScale = texture.vScale;
  48016. rtt.uAng = texture.uAng;
  48017. rtt.vAng = texture.vAng;
  48018. rtt.wAng = texture.wAng;
  48019. rtt.coordinatesIndex = texture.coordinatesIndex;
  48020. rtt.level = texture.level;
  48021. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  48022. rtt._texture.isReady = false;
  48023. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48024. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48025. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48026. passPostProcess.getEffect().executeWhenCompiled(function () {
  48027. passPostProcess.onApply = function (effect) {
  48028. effect.setTexture("textureSampler", texture);
  48029. };
  48030. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  48031. engine.unBindFramebuffer(rtt.getInternalTexture());
  48032. rtt.disposeFramebufferObjects();
  48033. passPostProcess.dispose();
  48034. rtt._texture.isReady = true;
  48035. });
  48036. return rtt;
  48037. };
  48038. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  48039. if (!scene._environmentBRDFTexture) {
  48040. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48041. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48042. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48043. scene._environmentBRDFTexture = texture;
  48044. }
  48045. return scene._environmentBRDFTexture;
  48046. };
  48047. 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=";
  48048. return TextureTools;
  48049. }());
  48050. BABYLON.TextureTools = TextureTools;
  48051. })(BABYLON || (BABYLON = {}));
  48052. //# sourceMappingURL=babylon.textureTools.js.map
  48053. var BABYLON;
  48054. (function (BABYLON) {
  48055. var SphericalPolynomial = (function () {
  48056. function SphericalPolynomial() {
  48057. this.x = BABYLON.Vector3.Zero();
  48058. this.y = BABYLON.Vector3.Zero();
  48059. this.z = BABYLON.Vector3.Zero();
  48060. this.xx = BABYLON.Vector3.Zero();
  48061. this.yy = BABYLON.Vector3.Zero();
  48062. this.zz = BABYLON.Vector3.Zero();
  48063. this.xy = BABYLON.Vector3.Zero();
  48064. this.yz = BABYLON.Vector3.Zero();
  48065. this.zx = BABYLON.Vector3.Zero();
  48066. }
  48067. SphericalPolynomial.prototype.addAmbient = function (color) {
  48068. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  48069. this.xx = this.xx.add(colorVector);
  48070. this.yy = this.yy.add(colorVector);
  48071. this.zz = this.zz.add(colorVector);
  48072. };
  48073. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  48074. var result = new SphericalPolynomial();
  48075. result.x = harmonics.L11.scale(1.02333);
  48076. result.y = harmonics.L1_1.scale(1.02333);
  48077. result.z = harmonics.L10.scale(1.02333);
  48078. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  48079. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  48080. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  48081. result.yz = harmonics.L2_1.scale(0.858086);
  48082. result.zx = harmonics.L21.scale(0.858086);
  48083. result.xy = harmonics.L2_2.scale(0.858086);
  48084. result.scale(1.0 / Math.PI);
  48085. return result;
  48086. };
  48087. SphericalPolynomial.prototype.scale = function (scale) {
  48088. this.x = this.x.scale(scale);
  48089. this.y = this.y.scale(scale);
  48090. this.z = this.z.scale(scale);
  48091. this.xx = this.xx.scale(scale);
  48092. this.yy = this.yy.scale(scale);
  48093. this.zz = this.zz.scale(scale);
  48094. this.yz = this.yz.scale(scale);
  48095. this.zx = this.zx.scale(scale);
  48096. this.xy = this.xy.scale(scale);
  48097. };
  48098. return SphericalPolynomial;
  48099. }());
  48100. BABYLON.SphericalPolynomial = SphericalPolynomial;
  48101. var SphericalHarmonics = (function () {
  48102. function SphericalHarmonics() {
  48103. this.L00 = BABYLON.Vector3.Zero();
  48104. this.L1_1 = BABYLON.Vector3.Zero();
  48105. this.L10 = BABYLON.Vector3.Zero();
  48106. this.L11 = BABYLON.Vector3.Zero();
  48107. this.L2_2 = BABYLON.Vector3.Zero();
  48108. this.L2_1 = BABYLON.Vector3.Zero();
  48109. this.L20 = BABYLON.Vector3.Zero();
  48110. this.L21 = BABYLON.Vector3.Zero();
  48111. this.L22 = BABYLON.Vector3.Zero();
  48112. }
  48113. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  48114. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  48115. var c = colorVector.scale(deltaSolidAngle);
  48116. this.L00 = this.L00.add(c.scale(0.282095));
  48117. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  48118. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  48119. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  48120. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  48121. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  48122. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  48123. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  48124. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  48125. };
  48126. SphericalHarmonics.prototype.scale = function (scale) {
  48127. this.L00 = this.L00.scale(scale);
  48128. this.L1_1 = this.L1_1.scale(scale);
  48129. this.L10 = this.L10.scale(scale);
  48130. this.L11 = this.L11.scale(scale);
  48131. this.L2_2 = this.L2_2.scale(scale);
  48132. this.L2_1 = this.L2_1.scale(scale);
  48133. this.L20 = this.L20.scale(scale);
  48134. this.L21 = this.L21.scale(scale);
  48135. this.L22 = this.L22.scale(scale);
  48136. };
  48137. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  48138. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  48139. //
  48140. // E_lm = A_l * L_lm
  48141. //
  48142. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  48143. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  48144. // the scaling factors are given in equation 9.
  48145. // Constant (Band 0)
  48146. this.L00 = this.L00.scale(3.141593);
  48147. // Linear (Band 1)
  48148. this.L1_1 = this.L1_1.scale(2.094395);
  48149. this.L10 = this.L10.scale(2.094395);
  48150. this.L11 = this.L11.scale(2.094395);
  48151. // Quadratic (Band 2)
  48152. this.L2_2 = this.L2_2.scale(0.785398);
  48153. this.L2_1 = this.L2_1.scale(0.785398);
  48154. this.L20 = this.L20.scale(0.785398);
  48155. this.L21 = this.L21.scale(0.785398);
  48156. this.L22 = this.L22.scale(0.785398);
  48157. };
  48158. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  48159. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  48160. // L = (1/pi) * E * rho
  48161. //
  48162. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  48163. this.scale(1.0 / Math.PI);
  48164. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  48165. // (The pixel shader must apply albedo after texture fetches, etc).
  48166. };
  48167. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  48168. var result = new SphericalHarmonics();
  48169. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  48170. result.L1_1 = polynomial.y.scale(0.977204);
  48171. result.L10 = polynomial.z.scale(0.977204);
  48172. result.L11 = polynomial.x.scale(0.977204);
  48173. result.L2_2 = polynomial.xy.scale(1.16538);
  48174. result.L2_1 = polynomial.yz.scale(1.16538);
  48175. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  48176. result.L21 = polynomial.zx.scale(1.16538);
  48177. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  48178. result.scale(Math.PI);
  48179. return result;
  48180. };
  48181. return SphericalHarmonics;
  48182. }());
  48183. BABYLON.SphericalHarmonics = SphericalHarmonics;
  48184. })(BABYLON || (BABYLON = {}));
  48185. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  48186. var BABYLON;
  48187. (function (BABYLON) {
  48188. var Internals;
  48189. (function (Internals) {
  48190. var FileFaceOrientation = (function () {
  48191. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  48192. this.name = name;
  48193. this.worldAxisForNormal = worldAxisForNormal;
  48194. this.worldAxisForFileX = worldAxisForFileX;
  48195. this.worldAxisForFileY = worldAxisForFileY;
  48196. }
  48197. return FileFaceOrientation;
  48198. }());
  48199. ;
  48200. /**
  48201. * Helper class dealing with the extraction of spherical polynomial dataArray
  48202. * from a cube map.
  48203. */
  48204. var CubeMapToSphericalPolynomialTools = (function () {
  48205. function CubeMapToSphericalPolynomialTools() {
  48206. }
  48207. /**
  48208. * Converts a texture to the according Spherical Polynomial data.
  48209. * This extracts the first 3 orders only as they are the only one used in the lighting.
  48210. *
  48211. * @param texture The texture to extract the information from.
  48212. * @return The Spherical Polynomial data.
  48213. */
  48214. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  48215. if (!texture.isCube) {
  48216. // Only supports cube Textures currently.
  48217. return null;
  48218. }
  48219. var size = texture.getSize().width;
  48220. var right = texture.readPixels(0);
  48221. var left = texture.readPixels(1);
  48222. var up;
  48223. var down;
  48224. if (texture.isRenderTarget) {
  48225. up = texture.readPixels(3);
  48226. down = texture.readPixels(2);
  48227. }
  48228. else {
  48229. up = texture.readPixels(2);
  48230. down = texture.readPixels(3);
  48231. }
  48232. var front = texture.readPixels(4);
  48233. var back = texture.readPixels(5);
  48234. var gammaSpace = texture.gammaSpace;
  48235. // Always read as RGBA.
  48236. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  48237. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  48238. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  48239. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  48240. }
  48241. var cubeInfo = {
  48242. size: size,
  48243. right: right,
  48244. left: left,
  48245. up: up,
  48246. down: down,
  48247. front: front,
  48248. back: back,
  48249. format: format,
  48250. type: type,
  48251. gammaSpace: gammaSpace,
  48252. };
  48253. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  48254. };
  48255. /**
  48256. * Converts a cubemap to the according Spherical Polynomial data.
  48257. * This extracts the first 3 orders only as they are the only one used in the lighting.
  48258. *
  48259. * @param cubeInfo The Cube map to extract the information from.
  48260. * @return The Spherical Polynomial data.
  48261. */
  48262. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  48263. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  48264. var totalSolidAngle = 0.0;
  48265. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  48266. var du = 2.0 / cubeInfo.size;
  48267. var dv = du;
  48268. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  48269. var minUV = du * 0.5 - 1.0;
  48270. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48271. var fileFace = this.FileFaces[faceIndex];
  48272. var dataArray = cubeInfo[fileFace.name];
  48273. var v = minUV;
  48274. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  48275. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  48276. // Because SP is still linear, so summation is fine in that basis.
  48277. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  48278. for (var y = 0; y < cubeInfo.size; y++) {
  48279. var u = minUV;
  48280. for (var x = 0; x < cubeInfo.size; x++) {
  48281. // World direction (not normalised)
  48282. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  48283. worldDirection.normalize();
  48284. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  48285. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  48286. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  48287. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  48288. // Handle Integer types.
  48289. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  48290. r /= 255;
  48291. g /= 255;
  48292. b /= 255;
  48293. }
  48294. // Handle Gamma space textures.
  48295. if (cubeInfo.gammaSpace) {
  48296. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  48297. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  48298. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  48299. }
  48300. var color = new BABYLON.Color3(r, g, b);
  48301. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48302. totalSolidAngle += deltaSolidAngle;
  48303. u += du;
  48304. }
  48305. v += dv;
  48306. }
  48307. }
  48308. // Solid angle for entire sphere is 4*pi
  48309. var sphereSolidAngle = 4.0 * Math.PI;
  48310. // Adjust the solid angle to allow for how many faces we processed.
  48311. var facesProcessed = 6.0;
  48312. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  48313. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  48314. // This is needed because the numerical integration over the cube uses a
  48315. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  48316. // and also to compensate for accumulative error due to float precision in the summation.
  48317. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  48318. sphericalHarmonics.scale(correctionFactor);
  48319. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  48320. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  48321. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  48322. };
  48323. CubeMapToSphericalPolynomialTools.FileFaces = [
  48324. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  48325. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  48326. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  48327. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  48328. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  48329. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  48330. ];
  48331. return CubeMapToSphericalPolynomialTools;
  48332. }());
  48333. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  48334. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48335. })(BABYLON || (BABYLON = {}));
  48336. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  48337. var BABYLON;
  48338. (function (BABYLON) {
  48339. var Internals;
  48340. (function (Internals) {
  48341. /**
  48342. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  48343. */
  48344. var PanoramaToCubeMapTools = (function () {
  48345. function PanoramaToCubeMapTools() {
  48346. }
  48347. /**
  48348. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  48349. *
  48350. * @param float32Array The source data.
  48351. * @param inputWidth The width of the input panorama.
  48352. * @param inputhHeight The height of the input panorama.
  48353. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  48354. * @return The cubemap data
  48355. */
  48356. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  48357. if (!float32Array) {
  48358. throw "ConvertPanoramaToCubemap: input cannot be null";
  48359. }
  48360. if (float32Array.length != inputWidth * inputHeight * 3) {
  48361. throw "ConvertPanoramaToCubemap: input size is wrong";
  48362. }
  48363. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  48364. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  48365. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  48366. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  48367. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  48368. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  48369. return {
  48370. front: textureFront,
  48371. back: textureBack,
  48372. left: textureLeft,
  48373. right: textureRight,
  48374. up: textureUp,
  48375. down: textureDown,
  48376. size: size,
  48377. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  48378. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  48379. gammaSpace: false,
  48380. };
  48381. };
  48382. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  48383. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  48384. var textureArray = new Float32Array(buffer);
  48385. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  48386. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  48387. var dy = 1 / texSize;
  48388. var fy = 0;
  48389. for (var y = 0; y < texSize; y++) {
  48390. var xv1 = faceData[0];
  48391. var xv2 = faceData[2];
  48392. for (var x = 0; x < texSize; x++) {
  48393. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  48394. v.normalize();
  48395. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  48396. // 3 channels per pixels
  48397. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  48398. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  48399. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  48400. xv1 = xv1.add(rotDX1);
  48401. xv2 = xv2.add(rotDX2);
  48402. }
  48403. fy += dy;
  48404. }
  48405. return textureArray;
  48406. };
  48407. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  48408. var theta = Math.atan2(vDir.z, vDir.x);
  48409. var phi = Math.acos(vDir.y);
  48410. while (theta < -Math.PI)
  48411. theta += 2 * Math.PI;
  48412. while (theta > Math.PI)
  48413. theta -= 2 * Math.PI;
  48414. var dx = theta / Math.PI;
  48415. var dy = phi / Math.PI;
  48416. // recenter.
  48417. dx = dx * 0.5 + 0.5;
  48418. var px = Math.round(dx * inputWidth);
  48419. if (px < 0)
  48420. px = 0;
  48421. else if (px >= inputWidth)
  48422. px = inputWidth - 1;
  48423. var py = Math.round(dy * inputHeight);
  48424. if (py < 0)
  48425. py = 0;
  48426. else if (py >= inputHeight)
  48427. py = inputHeight - 1;
  48428. var inputY = (inputHeight - py - 1);
  48429. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  48430. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  48431. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  48432. return {
  48433. r: r,
  48434. g: g,
  48435. b: b
  48436. };
  48437. };
  48438. PanoramaToCubeMapTools.FACE_FRONT = [
  48439. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48440. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48441. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48442. new BABYLON.Vector3(1.0, 1.0, -1.0)
  48443. ];
  48444. PanoramaToCubeMapTools.FACE_BACK = [
  48445. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48446. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48447. new BABYLON.Vector3(1.0, 1.0, 1.0),
  48448. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  48449. ];
  48450. PanoramaToCubeMapTools.FACE_RIGHT = [
  48451. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48452. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48453. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48454. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48455. ];
  48456. PanoramaToCubeMapTools.FACE_LEFT = [
  48457. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48458. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48459. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48460. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  48461. ];
  48462. PanoramaToCubeMapTools.FACE_DOWN = [
  48463. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48464. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48465. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48466. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48467. ];
  48468. PanoramaToCubeMapTools.FACE_UP = [
  48469. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48470. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48471. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48472. new BABYLON.Vector3(1.0, -1.0, -1.0)
  48473. ];
  48474. return PanoramaToCubeMapTools;
  48475. }());
  48476. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  48477. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48478. })(BABYLON || (BABYLON = {}));
  48479. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  48480. var BABYLON;
  48481. (function (BABYLON) {
  48482. var Internals;
  48483. (function (Internals) {
  48484. ;
  48485. /**
  48486. * This groups tools to convert HDR texture to native colors array.
  48487. */
  48488. var HDRTools = (function () {
  48489. function HDRTools() {
  48490. }
  48491. HDRTools.Ldexp = function (mantissa, exponent) {
  48492. if (exponent > 1023) {
  48493. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  48494. }
  48495. if (exponent < -1074) {
  48496. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  48497. }
  48498. return mantissa * Math.pow(2, exponent);
  48499. };
  48500. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  48501. if (exponent > 0) {
  48502. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  48503. float32array[index + 0] = red * exponent;
  48504. float32array[index + 1] = green * exponent;
  48505. float32array[index + 2] = blue * exponent;
  48506. }
  48507. else {
  48508. float32array[index + 0] = 0;
  48509. float32array[index + 1] = 0;
  48510. float32array[index + 2] = 0;
  48511. }
  48512. };
  48513. HDRTools.readStringLine = function (uint8array, startIndex) {
  48514. var line = "";
  48515. var character = "";
  48516. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  48517. character = String.fromCharCode(uint8array[i]);
  48518. if (character == "\n") {
  48519. break;
  48520. }
  48521. line += character;
  48522. }
  48523. return line;
  48524. };
  48525. /**
  48526. * Reads header information from an RGBE texture stored in a native array.
  48527. * More information on this format are available here:
  48528. * https://en.wikipedia.org/wiki/RGBE_image_format
  48529. *
  48530. * @param uint8array The binary file stored in native array.
  48531. * @return The header information.
  48532. */
  48533. HDRTools.RGBE_ReadHeader = function (uint8array) {
  48534. var height = 0;
  48535. var width = 0;
  48536. var line = this.readStringLine(uint8array, 0);
  48537. if (line[0] != '#' || line[1] != '?') {
  48538. throw "Bad HDR Format.";
  48539. }
  48540. var endOfHeader = false;
  48541. var findFormat = false;
  48542. var lineIndex = 0;
  48543. do {
  48544. lineIndex += (line.length + 1);
  48545. line = this.readStringLine(uint8array, lineIndex);
  48546. if (line == "FORMAT=32-bit_rle_rgbe") {
  48547. findFormat = true;
  48548. }
  48549. else if (line.length == 0) {
  48550. endOfHeader = true;
  48551. }
  48552. } while (!endOfHeader);
  48553. if (!findFormat) {
  48554. throw "HDR Bad header format, unsupported FORMAT";
  48555. }
  48556. lineIndex += (line.length + 1);
  48557. line = this.readStringLine(uint8array, lineIndex);
  48558. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  48559. var match = sizeRegexp.exec(line);
  48560. // TODO. Support +Y and -X if needed.
  48561. if (match.length < 3) {
  48562. throw "HDR Bad header format, no size";
  48563. }
  48564. width = parseInt(match[2]);
  48565. height = parseInt(match[1]);
  48566. if (width < 8 || width > 0x7fff) {
  48567. throw "HDR Bad header format, unsupported size";
  48568. }
  48569. lineIndex += (line.length + 1);
  48570. return {
  48571. height: height,
  48572. width: width,
  48573. dataPosition: lineIndex
  48574. };
  48575. };
  48576. /**
  48577. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  48578. * This RGBE texture needs to store the information as a panorama.
  48579. *
  48580. * More information on this format are available here:
  48581. * https://en.wikipedia.org/wiki/RGBE_image_format
  48582. *
  48583. * @param buffer The binary file stored in an array buffer.
  48584. * @param size The expected size of the extracted cubemap.
  48585. * @return The Cube Map information.
  48586. */
  48587. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  48588. var uint8array = new Uint8Array(buffer);
  48589. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  48590. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48591. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  48592. return cubeMapData;
  48593. };
  48594. /**
  48595. * Returns the pixels data extracted from an RGBE texture.
  48596. * This pixels will be stored left to right up to down in the R G B order in one array.
  48597. *
  48598. * More information on this format are available here:
  48599. * https://en.wikipedia.org/wiki/RGBE_image_format
  48600. *
  48601. * @param uint8array The binary file stored in an array buffer.
  48602. * @param hdrInfo The header information of the file.
  48603. * @return The pixels data in RGB right to left up to down order.
  48604. */
  48605. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  48606. // Keep for multi format supports.
  48607. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48608. };
  48609. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  48610. var num_scanlines = hdrInfo.height;
  48611. var scanline_width = hdrInfo.width;
  48612. var a, b, c, d, count;
  48613. var dataIndex = hdrInfo.dataPosition;
  48614. var index = 0, endIndex = 0, i = 0;
  48615. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  48616. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  48617. // 3 channels of 4 bytes per pixel in float.
  48618. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  48619. var resultArray = new Float32Array(resultBuffer);
  48620. // read in each successive scanline
  48621. while (num_scanlines > 0) {
  48622. a = uint8array[dataIndex++];
  48623. b = uint8array[dataIndex++];
  48624. c = uint8array[dataIndex++];
  48625. d = uint8array[dataIndex++];
  48626. if (a != 2 || b != 2 || (c & 0x80)) {
  48627. // this file is not run length encoded
  48628. throw "HDR Bad header format, not RLE";
  48629. }
  48630. if (((c << 8) | d) != scanline_width) {
  48631. throw "HDR Bad header format, wrong scan line width";
  48632. }
  48633. index = 0;
  48634. // read each of the four channels for the scanline into the buffer
  48635. for (i = 0; i < 4; i++) {
  48636. endIndex = (i + 1) * scanline_width;
  48637. while (index < endIndex) {
  48638. a = uint8array[dataIndex++];
  48639. b = uint8array[dataIndex++];
  48640. if (a > 128) {
  48641. // a run of the same value
  48642. count = a - 128;
  48643. if ((count == 0) || (count > endIndex - index)) {
  48644. throw "HDR Bad Format, bad scanline data (run)";
  48645. }
  48646. while (count-- > 0) {
  48647. scanLineArray[index++] = b;
  48648. }
  48649. }
  48650. else {
  48651. // a non-run
  48652. count = a;
  48653. if ((count == 0) || (count > endIndex - index)) {
  48654. throw "HDR Bad Format, bad scanline data (non-run)";
  48655. }
  48656. scanLineArray[index++] = b;
  48657. if (--count > 0) {
  48658. for (var j = 0; j < count; j++) {
  48659. scanLineArray[index++] = uint8array[dataIndex++];
  48660. }
  48661. }
  48662. }
  48663. }
  48664. }
  48665. // now convert data from buffer into floats
  48666. for (i = 0; i < scanline_width; i++) {
  48667. a = scanLineArray[i];
  48668. b = scanLineArray[i + scanline_width];
  48669. c = scanLineArray[i + 2 * scanline_width];
  48670. d = scanLineArray[i + 3 * scanline_width];
  48671. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  48672. }
  48673. num_scanlines--;
  48674. }
  48675. return resultArray;
  48676. };
  48677. return HDRTools;
  48678. }());
  48679. Internals.HDRTools = HDRTools;
  48680. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48681. })(BABYLON || (BABYLON = {}));
  48682. //# sourceMappingURL=babylon.hdr.js.map
  48683. var BABYLON;
  48684. (function (BABYLON) {
  48685. /**
  48686. * This represents a texture coming from an HDR input.
  48687. *
  48688. * The only supported format is currently panorama picture stored in RGBE format.
  48689. * Example of such files can be found on HDRLib: http://hdrlib.com/
  48690. */
  48691. var HDRCubeTexture = (function (_super) {
  48692. __extends(HDRCubeTexture, _super);
  48693. /**
  48694. * Instantiates an HDRTexture from the following parameters.
  48695. *
  48696. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  48697. * @param scene The scene the texture will be used in
  48698. * @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.
  48699. * @param noMipmap Forces to not generate the mipmap if true
  48700. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  48701. * @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)
  48702. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  48703. */
  48704. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  48705. if (noMipmap === void 0) { noMipmap = false; }
  48706. if (generateHarmonics === void 0) { generateHarmonics = true; }
  48707. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  48708. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  48709. if (onLoad === void 0) { onLoad = null; }
  48710. if (onError === void 0) { onError = null; }
  48711. var _this = _super.call(this, scene) || this;
  48712. _this._useInGammaSpace = false;
  48713. _this._generateHarmonics = true;
  48714. _this._isBABYLONPreprocessed = false;
  48715. _this._onLoad = null;
  48716. _this._onError = null;
  48717. /**
  48718. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  48719. */
  48720. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  48721. /**
  48722. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  48723. * This is usefull at run time to apply the good shader.
  48724. */
  48725. _this.isPMREM = false;
  48726. _this._isBlocking = true;
  48727. if (!url) {
  48728. return _this;
  48729. }
  48730. _this.name = url;
  48731. _this.url = url;
  48732. _this.hasAlpha = false;
  48733. _this.isCube = true;
  48734. _this._textureMatrix = BABYLON.Matrix.Identity();
  48735. _this._onLoad = onLoad;
  48736. _this._onError = onError;
  48737. _this.gammaSpace = false;
  48738. if (size) {
  48739. _this._isBABYLONPreprocessed = false;
  48740. _this._noMipmap = noMipmap;
  48741. _this._size = size;
  48742. _this._useInGammaSpace = useInGammaSpace;
  48743. _this._usePMREMGenerator = usePMREMGenerator &&
  48744. scene.getEngine().getCaps().textureLOD &&
  48745. _this.getScene().getEngine().getCaps().textureFloat &&
  48746. !_this._useInGammaSpace;
  48747. }
  48748. else {
  48749. _this._isBABYLONPreprocessed = true;
  48750. _this._noMipmap = false;
  48751. _this._useInGammaSpace = false;
  48752. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  48753. _this.getScene().getEngine().getCaps().textureFloat &&
  48754. !_this._useInGammaSpace;
  48755. }
  48756. _this.isPMREM = _this._usePMREMGenerator;
  48757. _this._texture = _this._getFromCache(url, _this._noMipmap);
  48758. if (!_this._texture) {
  48759. if (!scene.useDelayedTextureLoading) {
  48760. _this.loadTexture();
  48761. }
  48762. else {
  48763. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  48764. }
  48765. }
  48766. return _this;
  48767. }
  48768. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  48769. /**
  48770. * Gets wether or not the texture is blocking during loading.
  48771. */
  48772. get: function () {
  48773. return this._isBlocking;
  48774. },
  48775. /**
  48776. * Sets wether or not the texture is blocking during loading.
  48777. */
  48778. set: function (value) {
  48779. this._isBlocking = value;
  48780. },
  48781. enumerable: true,
  48782. configurable: true
  48783. });
  48784. /**
  48785. * Occurs when the file is a preprocessed .babylon.hdr file.
  48786. */
  48787. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  48788. var _this = this;
  48789. var mipLevels = 0;
  48790. var floatArrayView = null;
  48791. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  48792. var mips = [];
  48793. var startIndex = 30;
  48794. for (var level = 0; level < mipLevels; level++) {
  48795. mips.push([]);
  48796. // Fill each pixel of the mip level.
  48797. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  48798. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48799. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  48800. mips[level].push(faceData);
  48801. startIndex += faceSize;
  48802. }
  48803. }
  48804. return mips;
  48805. } : null;
  48806. var callback = function (buffer) {
  48807. // Create Native Array Views
  48808. var intArrayView = new Int32Array(buffer);
  48809. floatArrayView = new Float32Array(buffer);
  48810. // Fill header.
  48811. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  48812. _this._size = intArrayView[1]; // CubeMap max mip face size.
  48813. // Update Texture Information.
  48814. _this._texture.updateSize(_this._size, _this._size);
  48815. // Fill polynomial information.
  48816. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  48817. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  48818. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  48819. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  48820. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  48821. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  48822. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  48823. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  48824. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  48825. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  48826. _this.sphericalPolynomial = sphericalPolynomial;
  48827. // Fill pixel data.
  48828. mipLevels = intArrayView[29]; // Number of mip levels.
  48829. var startIndex = 30;
  48830. var data = [];
  48831. var faceSize = Math.pow(_this._size, 2) * 3;
  48832. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48833. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  48834. startIndex += faceSize;
  48835. }
  48836. var results = [];
  48837. var byteArray = null;
  48838. // Push each faces.
  48839. for (var k = 0; k < 6; k++) {
  48840. var dataFace = null;
  48841. // To be deprecated.
  48842. if (version === 1) {
  48843. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  48844. dataFace = data[j];
  48845. }
  48846. // If special cases.
  48847. if (!mipmapGenerator) {
  48848. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  48849. // 3 channels of 1 bytes per pixel in bytes.
  48850. var byteBuffer = new ArrayBuffer(faceSize);
  48851. byteArray = new Uint8Array(byteBuffer);
  48852. }
  48853. for (var i = 0; i < _this._size * _this._size; i++) {
  48854. // Put in gamma space if requested.
  48855. if (_this._useInGammaSpace) {
  48856. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  48857. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  48858. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  48859. }
  48860. // Convert to int texture for fallback.
  48861. if (byteArray) {
  48862. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  48863. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  48864. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  48865. // May use luminance instead if the result is not accurate.
  48866. var max = Math.max(Math.max(r, g), b);
  48867. if (max > 255) {
  48868. var scale = 255 / max;
  48869. r *= scale;
  48870. g *= scale;
  48871. b *= scale;
  48872. }
  48873. byteArray[(i * 3) + 0] = r;
  48874. byteArray[(i * 3) + 1] = g;
  48875. byteArray[(i * 3) + 2] = b;
  48876. }
  48877. }
  48878. }
  48879. // Fill the array accordingly.
  48880. if (byteArray) {
  48881. results.push(byteArray);
  48882. }
  48883. else {
  48884. results.push(dataFace);
  48885. }
  48886. }
  48887. return results;
  48888. };
  48889. 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);
  48890. };
  48891. /**
  48892. * Occurs when the file is raw .hdr file.
  48893. */
  48894. HDRCubeTexture.prototype.loadHDRTexture = function () {
  48895. var _this = this;
  48896. var callback = function (buffer) {
  48897. // Extract the raw linear data.
  48898. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  48899. // Generate harmonics if needed.
  48900. if (_this._generateHarmonics) {
  48901. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  48902. _this.sphericalPolynomial = sphericalPolynomial;
  48903. }
  48904. var results = [];
  48905. var byteArray = null;
  48906. // Push each faces.
  48907. for (var j = 0; j < 6; j++) {
  48908. // Create uintarray fallback.
  48909. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  48910. // 3 channels of 1 bytes per pixel in bytes.
  48911. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  48912. byteArray = new Uint8Array(byteBuffer);
  48913. }
  48914. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  48915. // If special cases.
  48916. if (_this._useInGammaSpace || byteArray) {
  48917. for (var i = 0; i < _this._size * _this._size; i++) {
  48918. // Put in gamma space if requested.
  48919. if (_this._useInGammaSpace) {
  48920. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  48921. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  48922. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  48923. }
  48924. // Convert to int texture for fallback.
  48925. if (byteArray) {
  48926. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  48927. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  48928. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  48929. // May use luminance instead if the result is not accurate.
  48930. var max = Math.max(Math.max(r, g), b);
  48931. if (max > 255) {
  48932. var scale = 255 / max;
  48933. r *= scale;
  48934. g *= scale;
  48935. b *= scale;
  48936. }
  48937. byteArray[(i * 3) + 0] = r;
  48938. byteArray[(i * 3) + 1] = g;
  48939. byteArray[(i * 3) + 2] = b;
  48940. }
  48941. }
  48942. }
  48943. if (byteArray) {
  48944. results.push(byteArray);
  48945. }
  48946. else {
  48947. results.push(dataFace);
  48948. }
  48949. }
  48950. return results;
  48951. };
  48952. var mipmapGenerator = null;
  48953. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  48954. // if (!this._noMipmap &&
  48955. // this._usePMREMGenerator) {
  48956. // mipmapGenerator = (data: ArrayBufferView[]) => {
  48957. // // Custom setup of the generator matching with the PBR shader values.
  48958. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  48959. // this._size,
  48960. // this._size,
  48961. // 0,
  48962. // 3,
  48963. // this.getScene().getEngine().getCaps().textureFloat,
  48964. // 2048,
  48965. // 0.25,
  48966. // false,
  48967. // true);
  48968. // return generator.filterCubeMap();
  48969. // };
  48970. // }
  48971. 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);
  48972. };
  48973. /**
  48974. * Starts the loading process of the texture.
  48975. */
  48976. HDRCubeTexture.prototype.loadTexture = function () {
  48977. if (this._isBABYLONPreprocessed) {
  48978. this.loadBabylonTexture();
  48979. }
  48980. else {
  48981. this.loadHDRTexture();
  48982. }
  48983. };
  48984. HDRCubeTexture.prototype.clone = function () {
  48985. var size = this._isBABYLONPreprocessed ? null : this._size;
  48986. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  48987. // Base texture
  48988. newTexture.level = this.level;
  48989. newTexture.wrapU = this.wrapU;
  48990. newTexture.wrapV = this.wrapV;
  48991. newTexture.coordinatesIndex = this.coordinatesIndex;
  48992. newTexture.coordinatesMode = this.coordinatesMode;
  48993. return newTexture;
  48994. };
  48995. // Methods
  48996. HDRCubeTexture.prototype.delayLoad = function () {
  48997. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  48998. return;
  48999. }
  49000. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49001. this._texture = this._getFromCache(this.url, this._noMipmap);
  49002. if (!this._texture) {
  49003. this.loadTexture();
  49004. }
  49005. };
  49006. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  49007. return this._textureMatrix;
  49008. };
  49009. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49010. this._textureMatrix = value;
  49011. };
  49012. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49013. var texture = null;
  49014. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  49015. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  49016. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  49017. texture.name = parsedTexture.name;
  49018. texture.hasAlpha = parsedTexture.hasAlpha;
  49019. texture.level = parsedTexture.level;
  49020. texture.coordinatesMode = parsedTexture.coordinatesMode;
  49021. texture.isBlocking = parsedTexture.isBlocking;
  49022. }
  49023. return texture;
  49024. };
  49025. HDRCubeTexture.prototype.serialize = function () {
  49026. if (!this.name) {
  49027. return null;
  49028. }
  49029. var serializationObject = {};
  49030. serializationObject.name = this.name;
  49031. serializationObject.hasAlpha = this.hasAlpha;
  49032. serializationObject.isCube = true;
  49033. serializationObject.level = this.level;
  49034. serializationObject.size = this._size;
  49035. serializationObject.coordinatesMode = this.coordinatesMode;
  49036. serializationObject.useInGammaSpace = this._useInGammaSpace;
  49037. serializationObject.generateHarmonics = this._generateHarmonics;
  49038. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  49039. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  49040. serializationObject.customType = "BABYLON.HDRCubeTexture";
  49041. serializationObject.noMipmap = this._noMipmap;
  49042. serializationObject.isBlocking = this._isBlocking;
  49043. return serializationObject;
  49044. };
  49045. /**
  49046. * Saves as a file the data contained in the texture in a binary format.
  49047. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  49048. * as the spherical used in the lighting.
  49049. * @param url The HDR file url.
  49050. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  49051. * @param onError Method called if any error happens during download.
  49052. * @return The packed binary data.
  49053. */
  49054. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  49055. if (onError === void 0) { onError = null; }
  49056. var callback = function (buffer) {
  49057. var data = new Blob([buffer], { type: 'application/octet-stream' });
  49058. // Returns a URL you can use as a href.
  49059. var objUrl = window.URL.createObjectURL(data);
  49060. // Simulates a link to it and click to dowload.
  49061. var a = document.createElement("a");
  49062. document.body.appendChild(a);
  49063. a.style.display = "none";
  49064. a.href = objUrl;
  49065. a.download = "envmap.babylon.hdr";
  49066. a.click();
  49067. };
  49068. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  49069. };
  49070. /**
  49071. * Serializes the data contained in the texture in a binary format.
  49072. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  49073. * as the spherical used in the lighting.
  49074. * @param url The HDR file url.
  49075. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  49076. * @param onError Method called if any error happens during download.
  49077. * @return The packed binary data.
  49078. */
  49079. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  49080. if (onError === void 0) { onError = null; }
  49081. // Needs the url tho create the texture.
  49082. if (!url) {
  49083. return null;
  49084. }
  49085. // Check Power of two size.
  49086. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  49087. return null;
  49088. }
  49089. // Coming Back in 3.1.
  49090. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  49091. return null;
  49092. };
  49093. HDRCubeTexture._facesMapping = [
  49094. "right",
  49095. "left",
  49096. "up",
  49097. "down",
  49098. "front",
  49099. "back"
  49100. ];
  49101. return HDRCubeTexture;
  49102. }(BABYLON.BaseTexture));
  49103. BABYLON.HDRCubeTexture = HDRCubeTexture;
  49104. })(BABYLON || (BABYLON = {}));
  49105. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  49106. var BABYLON;
  49107. (function (BABYLON) {
  49108. var DefaultLoadingScreen = (function () {
  49109. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  49110. if (_loadingText === void 0) { _loadingText = ""; }
  49111. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  49112. var _this = this;
  49113. this._renderingCanvas = _renderingCanvas;
  49114. this._loadingText = _loadingText;
  49115. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  49116. // Resize
  49117. this._resizeLoadingUI = function () {
  49118. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  49119. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  49120. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  49121. _this._loadingDiv.style.left = canvasRect.left + "px";
  49122. _this._loadingDiv.style.top = canvasRect.top + "px";
  49123. _this._loadingDiv.style.width = canvasRect.width + "px";
  49124. _this._loadingDiv.style.height = canvasRect.height + "px";
  49125. };
  49126. }
  49127. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  49128. if (this._loadingDiv) {
  49129. // Do not add a loading screen if there is already one
  49130. return;
  49131. }
  49132. this._loadingDiv = document.createElement("div");
  49133. this._loadingDiv.id = "babylonjsLoadingDiv";
  49134. this._loadingDiv.style.opacity = "0";
  49135. this._loadingDiv.style.transition = "opacity 1.5s ease";
  49136. // Loading text
  49137. this._loadingTextDiv = document.createElement("div");
  49138. this._loadingTextDiv.style.position = "absolute";
  49139. this._loadingTextDiv.style.left = "0";
  49140. this._loadingTextDiv.style.top = "50%";
  49141. this._loadingTextDiv.style.marginTop = "80px";
  49142. this._loadingTextDiv.style.width = "100%";
  49143. this._loadingTextDiv.style.height = "20px";
  49144. this._loadingTextDiv.style.fontFamily = "Arial";
  49145. this._loadingTextDiv.style.fontSize = "14px";
  49146. this._loadingTextDiv.style.color = "white";
  49147. this._loadingTextDiv.style.textAlign = "center";
  49148. this._loadingTextDiv.innerHTML = "Loading";
  49149. this._loadingDiv.appendChild(this._loadingTextDiv);
  49150. //set the predefined text
  49151. this._loadingTextDiv.innerHTML = this._loadingText;
  49152. // Generating keyframes
  49153. var style = document.createElement('style');
  49154. style.type = 'text/css';
  49155. 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 }";
  49156. style.innerHTML = keyFrames;
  49157. document.getElementsByTagName('head')[0].appendChild(style);
  49158. // Loading img
  49159. var imgBack = new Image();
  49160. 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";
  49161. imgBack.style.position = "absolute";
  49162. imgBack.style.left = "50%";
  49163. imgBack.style.top = "50%";
  49164. imgBack.style.marginLeft = "-60px";
  49165. imgBack.style.marginTop = "-60px";
  49166. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  49167. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  49168. imgBack.style.transformOrigin = "50% 50%";
  49169. imgBack.style.webkitTransformOrigin = "50% 50%";
  49170. this._loadingDiv.appendChild(imgBack);
  49171. this._resizeLoadingUI();
  49172. window.addEventListener("resize", this._resizeLoadingUI);
  49173. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  49174. document.body.appendChild(this._loadingDiv);
  49175. this._loadingDiv.style.opacity = "1";
  49176. };
  49177. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  49178. var _this = this;
  49179. if (!this._loadingDiv) {
  49180. return;
  49181. }
  49182. var onTransitionEnd = function () {
  49183. if (!_this._loadingDiv) {
  49184. return;
  49185. }
  49186. document.body.removeChild(_this._loadingDiv);
  49187. window.removeEventListener("resize", _this._resizeLoadingUI);
  49188. _this._loadingDiv = null;
  49189. };
  49190. this._loadingDiv.style.opacity = "0";
  49191. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  49192. };
  49193. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  49194. set: function (text) {
  49195. this._loadingText = text;
  49196. if (this._loadingTextDiv) {
  49197. this._loadingTextDiv.innerHTML = this._loadingText;
  49198. }
  49199. },
  49200. enumerable: true,
  49201. configurable: true
  49202. });
  49203. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  49204. get: function () {
  49205. return this._loadingDivBackgroundColor;
  49206. },
  49207. set: function (color) {
  49208. this._loadingDivBackgroundColor = color;
  49209. if (!this._loadingDiv) {
  49210. return;
  49211. }
  49212. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  49213. },
  49214. enumerable: true,
  49215. configurable: true
  49216. });
  49217. return DefaultLoadingScreen;
  49218. }());
  49219. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  49220. })(BABYLON || (BABYLON = {}));
  49221. //# sourceMappingURL=babylon.loadingScreen.js.map
  49222. var BABYLON;
  49223. (function (BABYLON) {
  49224. var SceneLoader = (function () {
  49225. function SceneLoader() {
  49226. }
  49227. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  49228. get: function () {
  49229. return 0;
  49230. },
  49231. enumerable: true,
  49232. configurable: true
  49233. });
  49234. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  49235. get: function () {
  49236. return 1;
  49237. },
  49238. enumerable: true,
  49239. configurable: true
  49240. });
  49241. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  49242. get: function () {
  49243. return 2;
  49244. },
  49245. enumerable: true,
  49246. configurable: true
  49247. });
  49248. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  49249. get: function () {
  49250. return 3;
  49251. },
  49252. enumerable: true,
  49253. configurable: true
  49254. });
  49255. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  49256. get: function () {
  49257. return SceneLoader._ForceFullSceneLoadingForIncremental;
  49258. },
  49259. set: function (value) {
  49260. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  49261. },
  49262. enumerable: true,
  49263. configurable: true
  49264. });
  49265. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  49266. get: function () {
  49267. return SceneLoader._ShowLoadingScreen;
  49268. },
  49269. set: function (value) {
  49270. SceneLoader._ShowLoadingScreen = value;
  49271. },
  49272. enumerable: true,
  49273. configurable: true
  49274. });
  49275. Object.defineProperty(SceneLoader, "loggingLevel", {
  49276. get: function () {
  49277. return SceneLoader._loggingLevel;
  49278. },
  49279. set: function (value) {
  49280. SceneLoader._loggingLevel = value;
  49281. },
  49282. enumerable: true,
  49283. configurable: true
  49284. });
  49285. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  49286. get: function () {
  49287. return SceneLoader._CleanBoneMatrixWeights;
  49288. },
  49289. set: function (value) {
  49290. SceneLoader._CleanBoneMatrixWeights = value;
  49291. },
  49292. enumerable: true,
  49293. configurable: true
  49294. });
  49295. SceneLoader._getDefaultPlugin = function () {
  49296. return SceneLoader._registeredPlugins[".babylon"];
  49297. };
  49298. SceneLoader._getPluginForExtension = function (extension) {
  49299. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  49300. if (registeredPlugin) {
  49301. return registeredPlugin;
  49302. }
  49303. return SceneLoader._getDefaultPlugin();
  49304. };
  49305. SceneLoader._getPluginForDirectLoad = function (data) {
  49306. for (var extension in SceneLoader._registeredPlugins) {
  49307. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  49308. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  49309. return SceneLoader._registeredPlugins[extension];
  49310. }
  49311. }
  49312. return SceneLoader._getDefaultPlugin();
  49313. };
  49314. SceneLoader._getPluginForFilename = function (sceneFilename) {
  49315. if (sceneFilename.name) {
  49316. sceneFilename = sceneFilename.name;
  49317. }
  49318. var dotPosition = sceneFilename.lastIndexOf(".");
  49319. var queryStringPosition = sceneFilename.indexOf("?");
  49320. if (queryStringPosition === -1) {
  49321. queryStringPosition = sceneFilename.length;
  49322. }
  49323. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  49324. return SceneLoader._getPluginForExtension(extension);
  49325. };
  49326. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  49327. SceneLoader._getDirectLoad = function (sceneFilename) {
  49328. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  49329. return sceneFilename.substr(5);
  49330. }
  49331. return null;
  49332. };
  49333. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49334. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  49335. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  49336. var plugin = registeredPlugin.plugin;
  49337. var useArrayBuffer = registeredPlugin.isBinary;
  49338. var database;
  49339. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  49340. var dataCallback = function (data) {
  49341. if (scene.isDisposed) {
  49342. onError("Scene has been disposed");
  49343. return;
  49344. }
  49345. scene.database = database;
  49346. try {
  49347. onSuccess(plugin, data);
  49348. }
  49349. catch (e) {
  49350. onError(null, e);
  49351. }
  49352. };
  49353. var manifestChecked = function (success) {
  49354. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  49355. onError(request.status + " " + request.statusText);
  49356. });
  49357. };
  49358. if (directLoad) {
  49359. dataCallback(directLoad);
  49360. return;
  49361. }
  49362. if (rootUrl.indexOf("file:") === -1) {
  49363. if (scene.getEngine().enableOfflineSupport) {
  49364. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  49365. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  49366. }
  49367. else {
  49368. manifestChecked(true);
  49369. }
  49370. }
  49371. else {
  49372. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  49373. }
  49374. };
  49375. // Public functions
  49376. SceneLoader.GetPluginForExtension = function (extension) {
  49377. return SceneLoader._getPluginForExtension(extension).plugin;
  49378. };
  49379. SceneLoader.RegisterPlugin = function (plugin) {
  49380. if (typeof plugin.extensions === "string") {
  49381. var extension = plugin.extensions;
  49382. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  49383. plugin: plugin,
  49384. isBinary: false
  49385. };
  49386. }
  49387. else {
  49388. var extensions = plugin.extensions;
  49389. Object.keys(extensions).forEach(function (extension) {
  49390. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  49391. plugin: plugin,
  49392. isBinary: extensions[extension].isBinary
  49393. };
  49394. });
  49395. }
  49396. };
  49397. /**
  49398. * Import meshes into a scene
  49399. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  49400. * @param rootUrl a string that defines the root url for scene and resources
  49401. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49402. * @param scene the instance of BABYLON.Scene to append to
  49403. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  49404. * @param onProgress a callback with a progress event for each file being loaded
  49405. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49406. */
  49407. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49408. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  49409. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  49410. return;
  49411. }
  49412. var loadingToken = {};
  49413. scene._addPendingData(loadingToken);
  49414. var errorHandler = function (message, exception) {
  49415. if (onError) {
  49416. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  49417. }
  49418. scene._removePendingData(loadingToken);
  49419. };
  49420. var progressHandler = function (event) {
  49421. if (onProgress) {
  49422. onProgress(event);
  49423. }
  49424. };
  49425. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  49426. if (plugin.importMesh) {
  49427. var syncedPlugin = plugin;
  49428. var meshes = [];
  49429. var particleSystems = [];
  49430. var skeletons = [];
  49431. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  49432. return;
  49433. }
  49434. if (onSuccess) {
  49435. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  49436. onSuccess(meshes, particleSystems, skeletons);
  49437. scene._removePendingData(loadingToken);
  49438. }
  49439. }
  49440. else {
  49441. var asyncedPlugin = plugin;
  49442. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  49443. if (onSuccess) {
  49444. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  49445. onSuccess(meshes, particleSystems, skeletons);
  49446. scene._removePendingData(loadingToken);
  49447. }
  49448. }, progressHandler, errorHandler);
  49449. }
  49450. }, progressHandler, errorHandler);
  49451. };
  49452. /**
  49453. * Load a scene
  49454. * @param rootUrl a string that defines the root url for scene and resources
  49455. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49456. * @param engine is the instance of BABYLON.Engine to use to create the scene
  49457. * @param onSuccess a callback with the scene when import succeeds
  49458. * @param onProgress a callback with a progress event for each file being loaded
  49459. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49460. */
  49461. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  49462. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  49463. };
  49464. /**
  49465. * Append a scene
  49466. * @param rootUrl a string that defines the root url for scene and resources
  49467. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  49468. * @param scene is the instance of BABYLON.Scene to append to
  49469. * @param onSuccess a callback with the scene when import succeeds
  49470. * @param onProgress a callback with a progress event for each file being loaded
  49471. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  49472. */
  49473. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  49474. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  49475. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  49476. return;
  49477. }
  49478. if (SceneLoader.ShowLoadingScreen) {
  49479. scene.getEngine().displayLoadingUI();
  49480. }
  49481. var loadingToken = {};
  49482. scene._addPendingData(loadingToken);
  49483. var errorHandler = function (message, exception) {
  49484. if (onError) {
  49485. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  49486. }
  49487. scene._removePendingData(loadingToken);
  49488. scene.getEngine().hideLoadingUI();
  49489. };
  49490. var progressHandler = function (event) {
  49491. if (onProgress) {
  49492. onProgress(event);
  49493. }
  49494. };
  49495. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  49496. if (plugin.load) {
  49497. var syncedPlugin = plugin;
  49498. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  49499. return;
  49500. }
  49501. if (onSuccess) {
  49502. onSuccess(scene);
  49503. }
  49504. scene.loadingPluginName = plugin.name;
  49505. scene._removePendingData(loadingToken);
  49506. }
  49507. else {
  49508. var asyncedPlugin = plugin;
  49509. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  49510. if (onSuccess) {
  49511. onSuccess(scene);
  49512. }
  49513. scene.loadingPluginName = plugin.name;
  49514. scene._removePendingData(loadingToken);
  49515. }, progressHandler, errorHandler);
  49516. }
  49517. if (SceneLoader.ShowLoadingScreen) {
  49518. scene.executeWhenReady(function () {
  49519. scene.getEngine().hideLoadingUI();
  49520. });
  49521. }
  49522. }, progressHandler, errorHandler);
  49523. };
  49524. // Flags
  49525. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  49526. SceneLoader._ShowLoadingScreen = true;
  49527. SceneLoader._CleanBoneMatrixWeights = false;
  49528. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  49529. // Members
  49530. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  49531. SceneLoader._registeredPlugins = {};
  49532. return SceneLoader;
  49533. }());
  49534. BABYLON.SceneLoader = SceneLoader;
  49535. ;
  49536. })(BABYLON || (BABYLON = {}));
  49537. //# sourceMappingURL=babylon.sceneLoader.js.map
  49538. var BABYLON;
  49539. (function (BABYLON) {
  49540. var Internals;
  49541. (function (Internals) {
  49542. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  49543. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49544. var parsedMaterial = parsedData.materials[index];
  49545. if (parsedMaterial.id === id) {
  49546. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49547. }
  49548. }
  49549. return null;
  49550. };
  49551. var isDescendantOf = function (mesh, names, hierarchyIds) {
  49552. for (var i in names) {
  49553. if (mesh.name === names[i]) {
  49554. hierarchyIds.push(mesh.id);
  49555. return true;
  49556. }
  49557. }
  49558. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  49559. hierarchyIds.push(mesh.id);
  49560. return true;
  49561. }
  49562. return false;
  49563. };
  49564. var logOperation = function (operation, producer) {
  49565. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  49566. };
  49567. BABYLON.SceneLoader.RegisterPlugin({
  49568. name: "babylon.js",
  49569. extensions: ".babylon",
  49570. canDirectLoad: function (data) {
  49571. if (data.indexOf("babylon") !== -1) {
  49572. return true;
  49573. }
  49574. return false;
  49575. },
  49576. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  49577. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49578. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49579. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49580. // and avoid problems with multiple concurrent .babylon loads.
  49581. var log = "importMesh has failed JSON parse";
  49582. try {
  49583. var parsedData = JSON.parse(data);
  49584. log = "";
  49585. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49586. if (!meshesNames) {
  49587. meshesNames = null;
  49588. }
  49589. else if (!Array.isArray(meshesNames)) {
  49590. meshesNames = [meshesNames];
  49591. }
  49592. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49593. var loadedSkeletonsIds = [];
  49594. var loadedMaterialsIds = [];
  49595. var hierarchyIds = [];
  49596. var index;
  49597. var cache;
  49598. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49599. var parsedMesh = parsedData.meshes[index];
  49600. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  49601. if (meshesNames !== null) {
  49602. // Remove found mesh name from list.
  49603. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  49604. }
  49605. //Geometry?
  49606. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  49607. //does the file contain geometries?
  49608. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  49609. //find the correct geometry and add it to the scene
  49610. var found = false;
  49611. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  49612. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  49613. return;
  49614. }
  49615. else {
  49616. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  49617. if (parsedGeometryData.id === parsedMesh.geometryId) {
  49618. switch (geometryType) {
  49619. case "boxes":
  49620. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  49621. break;
  49622. case "spheres":
  49623. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  49624. break;
  49625. case "cylinders":
  49626. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  49627. break;
  49628. case "toruses":
  49629. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  49630. break;
  49631. case "grounds":
  49632. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  49633. break;
  49634. case "planes":
  49635. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  49636. break;
  49637. case "torusKnots":
  49638. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  49639. break;
  49640. case "vertexData":
  49641. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  49642. break;
  49643. }
  49644. found = true;
  49645. }
  49646. });
  49647. }
  49648. });
  49649. if (found === false) {
  49650. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  49651. }
  49652. }
  49653. }
  49654. // Material ?
  49655. if (parsedMesh.materialId) {
  49656. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  49657. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49658. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  49659. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  49660. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  49661. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  49662. var subMatId = parsedMultiMaterial.materials[matIndex];
  49663. loadedMaterialsIds.push(subMatId);
  49664. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  49665. log += "\n\tMaterial " + mat.toString(fullDetails);
  49666. }
  49667. loadedMaterialsIds.push(parsedMultiMaterial.id);
  49668. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49669. materialFound = true;
  49670. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  49671. break;
  49672. }
  49673. }
  49674. }
  49675. if (materialFound === false) {
  49676. loadedMaterialsIds.push(parsedMesh.materialId);
  49677. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  49678. if (!mat) {
  49679. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  49680. }
  49681. else {
  49682. log += "\n\tMaterial " + mat.toString(fullDetails);
  49683. }
  49684. }
  49685. }
  49686. // Skeleton ?
  49687. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49688. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  49689. if (skeletonAlreadyLoaded === false) {
  49690. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  49691. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  49692. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  49693. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49694. skeletons.push(skeleton);
  49695. loadedSkeletonsIds.push(parsedSkeleton.id);
  49696. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  49697. }
  49698. }
  49699. }
  49700. }
  49701. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49702. meshes.push(mesh);
  49703. log += "\n\tMesh " + mesh.toString(fullDetails);
  49704. }
  49705. }
  49706. // Connecting parents
  49707. var currentMesh;
  49708. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49709. currentMesh = scene.meshes[index];
  49710. if (currentMesh._waitingParentId) {
  49711. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  49712. currentMesh._waitingParentId = undefined;
  49713. }
  49714. }
  49715. // freeze and compute world matrix application
  49716. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49717. currentMesh = scene.meshes[index];
  49718. if (currentMesh._waitingFreezeWorldMatrix) {
  49719. currentMesh.freezeWorldMatrix();
  49720. currentMesh._waitingFreezeWorldMatrix = undefined;
  49721. }
  49722. else {
  49723. currentMesh.computeWorldMatrix(true);
  49724. }
  49725. }
  49726. }
  49727. // Particles
  49728. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49729. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49730. var parsedParticleSystem = parsedData.particleSystems[index];
  49731. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  49732. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  49733. }
  49734. }
  49735. }
  49736. return true;
  49737. }
  49738. catch (err) {
  49739. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  49740. log = null;
  49741. throw err;
  49742. }
  49743. finally {
  49744. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49745. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49746. }
  49747. }
  49748. },
  49749. load: function (scene, data, rootUrl) {
  49750. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49751. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49752. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49753. // and avoid problems with multiple concurrent .babylon loads.
  49754. var log = "importScene has failed JSON parse";
  49755. try {
  49756. var parsedData = JSON.parse(data);
  49757. log = "";
  49758. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49759. // Scene
  49760. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  49761. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  49762. }
  49763. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  49764. scene.autoClear = parsedData.autoClear;
  49765. }
  49766. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  49767. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  49768. }
  49769. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  49770. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  49771. }
  49772. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  49773. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  49774. }
  49775. // Fog
  49776. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  49777. scene.fogMode = parsedData.fogMode;
  49778. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  49779. scene.fogStart = parsedData.fogStart;
  49780. scene.fogEnd = parsedData.fogEnd;
  49781. scene.fogDensity = parsedData.fogDensity;
  49782. log += "\tFog mode for scene: ";
  49783. switch (scene.fogMode) {
  49784. // getters not compiling, so using hardcoded
  49785. case 1:
  49786. log += "exp\n";
  49787. break;
  49788. case 2:
  49789. log += "exp2\n";
  49790. break;
  49791. case 3:
  49792. log += "linear\n";
  49793. break;
  49794. }
  49795. }
  49796. //Physics
  49797. if (parsedData.physicsEnabled) {
  49798. var physicsPlugin;
  49799. if (parsedData.physicsEngine === "cannon") {
  49800. physicsPlugin = new BABYLON.CannonJSPlugin();
  49801. }
  49802. else if (parsedData.physicsEngine === "oimo") {
  49803. physicsPlugin = new BABYLON.OimoJSPlugin();
  49804. }
  49805. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  49806. //else - default engine, which is currently oimo
  49807. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  49808. scene.enablePhysics(physicsGravity, physicsPlugin);
  49809. }
  49810. // Metadata
  49811. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  49812. scene.metadata = parsedData.metadata;
  49813. }
  49814. //collisions, if defined. otherwise, default is true
  49815. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  49816. scene.collisionsEnabled = parsedData.collisionsEnabled;
  49817. }
  49818. scene.workerCollisions = !!parsedData.workerCollisions;
  49819. var index;
  49820. var cache;
  49821. // Lights
  49822. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  49823. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  49824. var parsedLight = parsedData.lights[index];
  49825. var light = BABYLON.Light.Parse(parsedLight, scene);
  49826. log += (index === 0 ? "\n\tLights:" : "");
  49827. log += "\n\t\t" + light.toString(fullDetails);
  49828. }
  49829. }
  49830. // Animations
  49831. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  49832. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  49833. var parsedAnimation = parsedData.animations[index];
  49834. var animation = BABYLON.Animation.Parse(parsedAnimation);
  49835. scene.animations.push(animation);
  49836. log += (index === 0 ? "\n\tAnimations:" : "");
  49837. log += "\n\t\t" + animation.toString(fullDetails);
  49838. }
  49839. }
  49840. if (parsedData.autoAnimate) {
  49841. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  49842. }
  49843. // Materials
  49844. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  49845. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49846. var parsedMaterial = parsedData.materials[index];
  49847. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49848. log += (index === 0 ? "\n\tMaterials:" : "");
  49849. log += "\n\t\t" + mat.toString(fullDetails);
  49850. }
  49851. }
  49852. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49853. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  49854. var parsedMultiMaterial = parsedData.multiMaterials[index];
  49855. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49856. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  49857. log += "\n\t\t" + mmat.toString(fullDetails);
  49858. }
  49859. }
  49860. // Morph targets
  49861. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  49862. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  49863. var managerData = _a[_i];
  49864. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  49865. }
  49866. }
  49867. // Skeletons
  49868. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49869. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  49870. var parsedSkeleton = parsedData.skeletons[index];
  49871. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49872. log += (index === 0 ? "\n\tSkeletons:" : "");
  49873. log += "\n\t\t" + skeleton.toString(fullDetails);
  49874. }
  49875. }
  49876. // Geometries
  49877. var geometries = parsedData.geometries;
  49878. if (geometries !== undefined && geometries !== null) {
  49879. // Boxes
  49880. var boxes = geometries.boxes;
  49881. if (boxes !== undefined && boxes !== null) {
  49882. for (index = 0, cache = boxes.length; index < cache; index++) {
  49883. var parsedBox = boxes[index];
  49884. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  49885. }
  49886. }
  49887. // Spheres
  49888. var spheres = geometries.spheres;
  49889. if (spheres !== undefined && spheres !== null) {
  49890. for (index = 0, cache = spheres.length; index < cache; index++) {
  49891. var parsedSphere = spheres[index];
  49892. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  49893. }
  49894. }
  49895. // Cylinders
  49896. var cylinders = geometries.cylinders;
  49897. if (cylinders !== undefined && cylinders !== null) {
  49898. for (index = 0, cache = cylinders.length; index < cache; index++) {
  49899. var parsedCylinder = cylinders[index];
  49900. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  49901. }
  49902. }
  49903. // Toruses
  49904. var toruses = geometries.toruses;
  49905. if (toruses !== undefined && toruses !== null) {
  49906. for (index = 0, cache = toruses.length; index < cache; index++) {
  49907. var parsedTorus = toruses[index];
  49908. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  49909. }
  49910. }
  49911. // Grounds
  49912. var grounds = geometries.grounds;
  49913. if (grounds !== undefined && grounds !== null) {
  49914. for (index = 0, cache = grounds.length; index < cache; index++) {
  49915. var parsedGround = grounds[index];
  49916. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  49917. }
  49918. }
  49919. // Planes
  49920. var planes = geometries.planes;
  49921. if (planes !== undefined && planes !== null) {
  49922. for (index = 0, cache = planes.length; index < cache; index++) {
  49923. var parsedPlane = planes[index];
  49924. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  49925. }
  49926. }
  49927. // TorusKnots
  49928. var torusKnots = geometries.torusKnots;
  49929. if (torusKnots !== undefined && torusKnots !== null) {
  49930. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  49931. var parsedTorusKnot = torusKnots[index];
  49932. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  49933. }
  49934. }
  49935. // VertexData
  49936. var vertexData = geometries.vertexData;
  49937. if (vertexData !== undefined && vertexData !== null) {
  49938. for (index = 0, cache = vertexData.length; index < cache; index++) {
  49939. var parsedVertexData = vertexData[index];
  49940. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  49941. }
  49942. }
  49943. }
  49944. // Meshes
  49945. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49946. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49947. var parsedMesh = parsedData.meshes[index];
  49948. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49949. log += (index === 0 ? "\n\tMeshes:" : "");
  49950. log += "\n\t\t" + mesh.toString(fullDetails);
  49951. }
  49952. }
  49953. // Cameras
  49954. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  49955. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  49956. var parsedCamera = parsedData.cameras[index];
  49957. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  49958. log += (index === 0 ? "\n\tCameras:" : "");
  49959. log += "\n\t\t" + camera.toString(fullDetails);
  49960. }
  49961. }
  49962. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  49963. scene.setActiveCameraByID(parsedData.activeCameraID);
  49964. }
  49965. // Browsing all the graph to connect the dots
  49966. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  49967. var camera = scene.cameras[index];
  49968. if (camera._waitingParentId) {
  49969. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  49970. camera._waitingParentId = undefined;
  49971. }
  49972. }
  49973. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49974. var light = scene.lights[index];
  49975. if (light._waitingParentId) {
  49976. light.parent = scene.getLastEntryByID(light._waitingParentId);
  49977. light._waitingParentId = undefined;
  49978. }
  49979. }
  49980. // Sounds
  49981. var loadedSounds = [];
  49982. var loadedSound;
  49983. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  49984. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  49985. var parsedSound = parsedData.sounds[index];
  49986. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49987. if (!parsedSound.url)
  49988. parsedSound.url = parsedSound.name;
  49989. if (!loadedSounds[parsedSound.url]) {
  49990. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  49991. loadedSounds[parsedSound.url] = loadedSound;
  49992. }
  49993. else {
  49994. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  49995. }
  49996. }
  49997. else {
  49998. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  49999. }
  50000. }
  50001. }
  50002. loadedSounds = [];
  50003. // Connect parents & children and parse actions
  50004. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  50005. var mesh = scene.meshes[index];
  50006. if (mesh._waitingParentId) {
  50007. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  50008. mesh._waitingParentId = undefined;
  50009. }
  50010. if (mesh._waitingActions) {
  50011. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  50012. mesh._waitingActions = undefined;
  50013. }
  50014. }
  50015. // freeze world matrix application
  50016. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  50017. var currentMesh = scene.meshes[index];
  50018. if (currentMesh._waitingFreezeWorldMatrix) {
  50019. currentMesh.freezeWorldMatrix();
  50020. currentMesh._waitingFreezeWorldMatrix = undefined;
  50021. }
  50022. else {
  50023. currentMesh.computeWorldMatrix(true);
  50024. }
  50025. }
  50026. // Particles Systems
  50027. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  50028. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  50029. var parsedParticleSystem = parsedData.particleSystems[index];
  50030. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  50031. }
  50032. }
  50033. // Lens flares
  50034. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  50035. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  50036. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  50037. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  50038. }
  50039. }
  50040. // Shadows
  50041. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  50042. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  50043. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  50044. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  50045. }
  50046. }
  50047. // Lights exclusions / inclusions
  50048. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  50049. var light = scene.lights[index];
  50050. // Excluded check
  50051. if (light._excludedMeshesIds.length > 0) {
  50052. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  50053. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  50054. if (excludedMesh) {
  50055. light.excludedMeshes.push(excludedMesh);
  50056. }
  50057. }
  50058. light._excludedMeshesIds = [];
  50059. }
  50060. // Included check
  50061. if (light._includedOnlyMeshesIds.length > 0) {
  50062. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  50063. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  50064. if (includedOnlyMesh) {
  50065. light.includedOnlyMeshes.push(includedOnlyMesh);
  50066. }
  50067. }
  50068. light._includedOnlyMeshesIds = [];
  50069. }
  50070. }
  50071. // Actions (scene)
  50072. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  50073. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  50074. }
  50075. // Finish
  50076. return true;
  50077. }
  50078. catch (err) {
  50079. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  50080. log = null;
  50081. throw err;
  50082. }
  50083. finally {
  50084. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  50085. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  50086. }
  50087. }
  50088. }
  50089. });
  50090. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50091. })(BABYLON || (BABYLON = {}));
  50092. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  50093. var BABYLON;
  50094. (function (BABYLON) {
  50095. var FilesInput = (function () {
  50096. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback) {
  50097. this._engine = engine;
  50098. this._currentScene = scene;
  50099. this._sceneLoadedCallback = sceneLoadedCallback;
  50100. this._progressCallback = progressCallback;
  50101. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  50102. this._textureLoadingCallback = textureLoadingCallback;
  50103. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  50104. this._onReloadCallback = onReloadCallback;
  50105. }
  50106. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  50107. var _this = this;
  50108. if (elementToMonitor) {
  50109. this._elementToMonitor = elementToMonitor;
  50110. this._dragEnterHandler = function (e) { _this.drag(e); };
  50111. this._dragOverHandler = function (e) { _this.drag(e); };
  50112. this._dropHandler = function (e) { _this.drop(e); };
  50113. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  50114. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  50115. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  50116. }
  50117. };
  50118. FilesInput.prototype.dispose = function () {
  50119. if (!this._elementToMonitor) {
  50120. return;
  50121. }
  50122. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  50123. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  50124. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  50125. };
  50126. FilesInput.prototype.renderFunction = function () {
  50127. if (this._additionalRenderLoopLogicCallback) {
  50128. this._additionalRenderLoopLogicCallback();
  50129. }
  50130. if (this._currentScene) {
  50131. if (this._textureLoadingCallback) {
  50132. var remaining = this._currentScene.getWaitingItemsCount();
  50133. if (remaining > 0) {
  50134. this._textureLoadingCallback(remaining);
  50135. }
  50136. }
  50137. this._currentScene.render();
  50138. }
  50139. };
  50140. FilesInput.prototype.drag = function (e) {
  50141. e.stopPropagation();
  50142. e.preventDefault();
  50143. };
  50144. FilesInput.prototype.drop = function (eventDrop) {
  50145. eventDrop.stopPropagation();
  50146. eventDrop.preventDefault();
  50147. this.loadFiles(eventDrop);
  50148. };
  50149. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  50150. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  50151. reader.readEntries(function (fileEntries) {
  50152. var remaining = fileEntries.length;
  50153. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  50154. var fileEntry = fileEntries_1[_i];
  50155. if (fileEntry.isFile) {
  50156. fileEntry.file(function (file) {
  50157. file.correctName = relativePath + file.name;
  50158. files.push(file);
  50159. remaining--;
  50160. if (remaining === 0) {
  50161. callback();
  50162. }
  50163. });
  50164. }
  50165. else {
  50166. remaining--;
  50167. if (remaining === 0) {
  50168. callback();
  50169. }
  50170. }
  50171. }
  50172. });
  50173. };
  50174. FilesInput.prototype._processFiles = function (files) {
  50175. for (var i = 0; i < files.length; i++) {
  50176. var name = files[i].correctName.toLowerCase();
  50177. var extension = name.split('.').pop();
  50178. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  50179. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  50180. this._sceneFileToLoad = files[i];
  50181. }
  50182. else {
  50183. FilesInput.FilesToLoad[name] = files[i];
  50184. }
  50185. }
  50186. if (this._onReloadCallback) {
  50187. this._onReloadCallback(this._sceneFileToLoad);
  50188. }
  50189. else {
  50190. this.reload();
  50191. }
  50192. };
  50193. FilesInput.prototype.loadFiles = function (event) {
  50194. var _this = this;
  50195. if (this._startingProcessingFilesCallback)
  50196. this._startingProcessingFilesCallback();
  50197. // Handling data transfer via drag'n'drop
  50198. if (event && event.dataTransfer && event.dataTransfer.files) {
  50199. this._filesToLoad = event.dataTransfer.files;
  50200. }
  50201. // Handling files from input files
  50202. if (event && event.target && event.target.files) {
  50203. this._filesToLoad = event.target.files;
  50204. }
  50205. if (this._filesToLoad && this._filesToLoad.length > 0) {
  50206. var files_1 = [];
  50207. var folders = [];
  50208. var items = event.dataTransfer ? event.dataTransfer.items : null;
  50209. for (var i = 0; i < this._filesToLoad.length; i++) {
  50210. var fileToLoad = this._filesToLoad[i];
  50211. var name_1 = fileToLoad.name.toLowerCase();
  50212. var type = fileToLoad.type;
  50213. var entry = void 0;
  50214. fileToLoad.correctName = name_1;
  50215. if (items) {
  50216. var item = items[i];
  50217. if (item.getAsEntry) {
  50218. entry = item.getAsEntry();
  50219. }
  50220. else if (item.webkitGetAsEntry) {
  50221. entry = item.webkitGetAsEntry();
  50222. }
  50223. }
  50224. if (!entry) {
  50225. files_1.push(fileToLoad);
  50226. }
  50227. else {
  50228. if (entry.isDirectory) {
  50229. folders.push(entry);
  50230. }
  50231. else {
  50232. files_1.push(fileToLoad);
  50233. }
  50234. }
  50235. }
  50236. if (folders.length === 0) {
  50237. this._processFiles(files_1);
  50238. }
  50239. else {
  50240. var remaining = folders.length;
  50241. // Extract folder content
  50242. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  50243. var folder = folders_1[_i];
  50244. this._handleFolderDrop(folder, files_1, function () {
  50245. remaining--;
  50246. if (remaining === 0) {
  50247. _this._processFiles(files_1);
  50248. }
  50249. });
  50250. }
  50251. }
  50252. }
  50253. };
  50254. FilesInput.prototype.reload = function () {
  50255. var _this = this;
  50256. // If a ".babylon" file has been provided
  50257. if (this._sceneFileToLoad) {
  50258. if (this._currentScene) {
  50259. if (BABYLON.Tools.errorsCount > 0) {
  50260. BABYLON.Tools.ClearLogCache();
  50261. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  50262. }
  50263. this._engine.stopRenderLoop();
  50264. this._currentScene.dispose();
  50265. }
  50266. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  50267. _this._currentScene = newScene;
  50268. if (_this._sceneLoadedCallback) {
  50269. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  50270. }
  50271. // Wait for textures and shaders to be ready
  50272. _this._currentScene.executeWhenReady(function () {
  50273. _this._engine.runRenderLoop(function () {
  50274. _this.renderFunction();
  50275. });
  50276. });
  50277. }, function (progress) {
  50278. if (_this._progressCallback) {
  50279. _this._progressCallback(progress);
  50280. }
  50281. });
  50282. }
  50283. else {
  50284. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  50285. }
  50286. };
  50287. FilesInput.FilesToLoad = new Array();
  50288. return FilesInput;
  50289. }());
  50290. BABYLON.FilesInput = FilesInput;
  50291. })(BABYLON || (BABYLON = {}));
  50292. //# sourceMappingURL=babylon.filesInput.js.map
  50293. var BABYLON;
  50294. (function (BABYLON) {
  50295. var FramingBehavior = (function () {
  50296. function FramingBehavior() {
  50297. this._mode = FramingBehavior.FitFrustumSidesMode;
  50298. this._radiusScale = 1.0;
  50299. this._positionScale = 0.5;
  50300. this._defaultElevation = 0.3;
  50301. this._elevationReturnTime = 1500;
  50302. this._elevationReturnWaitTime = 1000;
  50303. this._zoomStopsAnimation = false;
  50304. this._framingTime = 1500;
  50305. this._isPointerDown = false;
  50306. this._lastFrameTime = null;
  50307. this._lastInteractionTime = -Infinity;
  50308. // Framing control
  50309. this._animatables = new Array();
  50310. this._betaIsAnimating = false;
  50311. this._lastFrameRadius = 0;
  50312. }
  50313. Object.defineProperty(FramingBehavior.prototype, "name", {
  50314. get: function () {
  50315. return "Framing";
  50316. },
  50317. enumerable: true,
  50318. configurable: true
  50319. });
  50320. Object.defineProperty(FramingBehavior.prototype, "mode", {
  50321. /**
  50322. * Gets current mode used by the behavior.
  50323. */
  50324. get: function () {
  50325. return this._mode;
  50326. },
  50327. /**
  50328. * Sets the current mode used by the behavior
  50329. */
  50330. set: function (mode) {
  50331. this._mode = mode;
  50332. },
  50333. enumerable: true,
  50334. configurable: true
  50335. });
  50336. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  50337. /**
  50338. * Gets the scale applied to the radius
  50339. */
  50340. get: function () {
  50341. return this._radiusScale;
  50342. },
  50343. /**
  50344. * Sets the scale applied to the radius (1 by default)
  50345. */
  50346. set: function (radius) {
  50347. this._radiusScale = radius;
  50348. },
  50349. enumerable: true,
  50350. configurable: true
  50351. });
  50352. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  50353. /**
  50354. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  50355. */
  50356. get: function () {
  50357. return this._positionScale;
  50358. },
  50359. /**
  50360. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  50361. */
  50362. set: function (scale) {
  50363. this._positionScale = scale;
  50364. },
  50365. enumerable: true,
  50366. configurable: true
  50367. });
  50368. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  50369. /**
  50370. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  50371. * behaviour is triggered, in radians.
  50372. */
  50373. get: function () {
  50374. return this._defaultElevation;
  50375. },
  50376. /**
  50377. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  50378. * behaviour is triggered, in radians.
  50379. */
  50380. set: function (elevation) {
  50381. this._defaultElevation = elevation;
  50382. },
  50383. enumerable: true,
  50384. configurable: true
  50385. });
  50386. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  50387. /**
  50388. * Gets the time (in milliseconds) taken to return to the default beta position.
  50389. * Negative value indicates camera should not return to default.
  50390. */
  50391. get: function () {
  50392. return this._elevationReturnTime;
  50393. },
  50394. /**
  50395. * Sets the time (in milliseconds) taken to return to the default beta position.
  50396. * Negative value indicates camera should not return to default.
  50397. */
  50398. set: function (speed) {
  50399. this._elevationReturnTime = speed;
  50400. },
  50401. enumerable: true,
  50402. configurable: true
  50403. });
  50404. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  50405. /**
  50406. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  50407. */
  50408. get: function () {
  50409. return this._elevationReturnWaitTime;
  50410. },
  50411. /**
  50412. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  50413. */
  50414. set: function (time) {
  50415. this._elevationReturnWaitTime = time;
  50416. },
  50417. enumerable: true,
  50418. configurable: true
  50419. });
  50420. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  50421. /**
  50422. * Gets the flag that indicates if user zooming should stop animation.
  50423. */
  50424. get: function () {
  50425. return this._zoomStopsAnimation;
  50426. },
  50427. /**
  50428. * Sets the flag that indicates if user zooming should stop animation.
  50429. */
  50430. set: function (flag) {
  50431. this._zoomStopsAnimation = flag;
  50432. },
  50433. enumerable: true,
  50434. configurable: true
  50435. });
  50436. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  50437. /**
  50438. * Gets the transition time when framing the mesh, in milliseconds
  50439. */
  50440. get: function () {
  50441. return this._framingTime;
  50442. },
  50443. /**
  50444. * Sets the transition time when framing the mesh, in milliseconds
  50445. */
  50446. set: function (time) {
  50447. this._framingTime = time;
  50448. },
  50449. enumerable: true,
  50450. configurable: true
  50451. });
  50452. FramingBehavior.prototype.attach = function (camera) {
  50453. var _this = this;
  50454. this._attachedCamera = camera;
  50455. var scene = this._attachedCamera.getScene();
  50456. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  50457. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  50458. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50459. _this._isPointerDown = true;
  50460. return;
  50461. }
  50462. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  50463. _this._isPointerDown = false;
  50464. }
  50465. });
  50466. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  50467. if (mesh) {
  50468. _this.zoomOnMesh(mesh);
  50469. }
  50470. });
  50471. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50472. // Stop the animation if there is user interaction and the animation should stop for this interaction
  50473. _this._applyUserInteraction();
  50474. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  50475. // back to the default position after a given timeout
  50476. _this._maintainCameraAboveGround();
  50477. });
  50478. };
  50479. FramingBehavior.prototype.detach = function () {
  50480. var scene = this._attachedCamera.getScene();
  50481. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  50482. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50483. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50484. this._attachedCamera = null;
  50485. };
  50486. /**
  50487. * Targets the given mesh and updates zoom level accordingly.
  50488. * @param mesh The mesh to target.
  50489. * @param radius Optional. If a cached radius position already exists, overrides default.
  50490. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  50491. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  50492. */
  50493. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ) {
  50494. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  50495. mesh.computeWorldMatrix(true);
  50496. var boundingBox = mesh.getBoundingInfo().boundingBox;
  50497. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ);
  50498. };
  50499. /**
  50500. * Targets the given mesh and updates zoom level accordingly.
  50501. * @param mesh The mesh to target.
  50502. * @param radius Optional. If a cached radius position already exists, overrides default.
  50503. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  50504. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  50505. */
  50506. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ) {
  50507. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  50508. var zoomTarget;
  50509. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  50510. var bottom = minimumWorld.y;
  50511. var top = maximumWorld.y;
  50512. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  50513. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  50514. if (focusOnOriginXZ) {
  50515. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  50516. }
  50517. else {
  50518. var centerWorld = minimumWorld.add(radiusWorld);
  50519. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  50520. }
  50521. if (!this._vectorTransition) {
  50522. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  50523. }
  50524. this._betaIsAnimating = true;
  50525. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  50526. // sets the radius and lower radius bounds
  50527. // Small delta ensures camera is not always at lower zoom limit.
  50528. var delta = 0.1;
  50529. var radius = 0;
  50530. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  50531. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  50532. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  50533. radius = position;
  50534. }
  50535. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  50536. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  50537. if (this._attachedCamera.lowerRadiusLimit === null) {
  50538. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  50539. }
  50540. }
  50541. // transition to new radius
  50542. if (!this._radiusTransition) {
  50543. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  50544. }
  50545. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime));
  50546. };
  50547. /**
  50548. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  50549. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  50550. * frustum width.
  50551. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  50552. * to fully enclose the mesh in the viewing frustum.
  50553. */
  50554. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  50555. var size = maximumWorld.subtract(minimumWorld);
  50556. var boxVectorGlobalDiagonal = size.length();
  50557. var frustumSlope = this._getFrustumSlope();
  50558. // Formula for setting distance
  50559. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  50560. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  50561. // Horizon distance
  50562. var radius = radiusWithoutFraming * this._radiusScale;
  50563. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  50564. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  50565. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  50566. var camera = this._attachedCamera;
  50567. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  50568. // Don't exceed the requested limit
  50569. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  50570. }
  50571. // Don't exceed the upper radius limit
  50572. if (camera.upperRadiusLimit) {
  50573. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  50574. }
  50575. return distance;
  50576. };
  50577. /**
  50578. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  50579. * is automatically returned to its default position (expected to be above ground plane).
  50580. */
  50581. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  50582. var _this = this;
  50583. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  50584. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  50585. var limitBeta = Math.PI * 0.5;
  50586. // Bring the camera back up if below the ground plane
  50587. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  50588. this._betaIsAnimating = true;
  50589. //Transition to new position
  50590. this.stopAllAnimations();
  50591. if (!this._betaTransition) {
  50592. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  50593. }
  50594. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  50595. _this._clearAnimationLocks();
  50596. _this.stopAllAnimations();
  50597. }));
  50598. }
  50599. };
  50600. /**
  50601. * Returns the frustum slope based on the canvas ratio and camera FOV
  50602. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  50603. */
  50604. FramingBehavior.prototype._getFrustumSlope = function () {
  50605. // Calculate the viewport ratio
  50606. // Aspect Ratio is Height/Width.
  50607. var camera = this._attachedCamera;
  50608. var engine = camera.getScene().getEngine();
  50609. var aspectRatio = engine.getAspectRatio(camera);
  50610. // Camera FOV is the vertical field of view (top-bottom) in radians.
  50611. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  50612. var frustumSlopeY = Math.tan(camera.fov / 2);
  50613. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  50614. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  50615. // along the forward vector.
  50616. var frustumSlopeX = frustumSlopeY * aspectRatio;
  50617. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  50618. };
  50619. /**
  50620. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  50621. */
  50622. FramingBehavior.prototype._clearAnimationLocks = function () {
  50623. this._betaIsAnimating = false;
  50624. };
  50625. /**
  50626. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  50627. */
  50628. FramingBehavior.prototype._applyUserInteraction = function () {
  50629. if (this.isUserIsMoving) {
  50630. this._lastInteractionTime = BABYLON.Tools.Now;
  50631. this.stopAllAnimations();
  50632. this._clearAnimationLocks();
  50633. }
  50634. };
  50635. /**
  50636. * Stops and removes all animations that have been applied to the camera
  50637. */
  50638. FramingBehavior.prototype.stopAllAnimations = function () {
  50639. this._attachedCamera.animations = [];
  50640. while (this._animatables.length) {
  50641. if (this._animatables[0]) {
  50642. this._animatables[0].onAnimationEnd = null;
  50643. this._animatables[0].stop();
  50644. }
  50645. this._animatables.shift();
  50646. }
  50647. };
  50648. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  50649. /**
  50650. * Gets a value indicating if the user is moving the camera
  50651. */
  50652. get: function () {
  50653. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  50654. this._attachedCamera.inertialBetaOffset !== 0 ||
  50655. this._attachedCamera.inertialRadiusOffset !== 0 ||
  50656. this._attachedCamera.inertialPanningX !== 0 ||
  50657. this._attachedCamera.inertialPanningY !== 0 ||
  50658. this._isPointerDown;
  50659. },
  50660. enumerable: true,
  50661. configurable: true
  50662. });
  50663. /**
  50664. * The easing function used by animations
  50665. */
  50666. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  50667. /**
  50668. * The easing mode used by animations
  50669. */
  50670. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  50671. // Statics
  50672. /**
  50673. * The camera can move all the way towards the mesh.
  50674. */
  50675. FramingBehavior.IgnoreBoundsSizeMode = 0;
  50676. /**
  50677. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  50678. */
  50679. FramingBehavior.FitFrustumSidesMode = 1;
  50680. return FramingBehavior;
  50681. }());
  50682. BABYLON.FramingBehavior = FramingBehavior;
  50683. })(BABYLON || (BABYLON = {}));
  50684. //# sourceMappingURL=babylon.framingBehavior.js.map
  50685. var BABYLON;
  50686. (function (BABYLON) {
  50687. /**
  50688. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  50689. */
  50690. var BouncingBehavior = (function () {
  50691. function BouncingBehavior() {
  50692. /**
  50693. * The duration of the animation, in milliseconds
  50694. */
  50695. this.transitionDuration = 450;
  50696. /**
  50697. * Length of the distance animated by the transition when lower radius is reached
  50698. */
  50699. this.lowerRadiusTransitionRange = 2;
  50700. /**
  50701. * Length of the distance animated by the transition when upper radius is reached
  50702. */
  50703. this.upperRadiusTransitionRange = -2;
  50704. this._autoTransitionRange = false;
  50705. // Animations
  50706. this._radiusIsAnimating = false;
  50707. this._radiusBounceTransition = null;
  50708. this._animatables = new Array();
  50709. }
  50710. Object.defineProperty(BouncingBehavior.prototype, "name", {
  50711. get: function () {
  50712. return "Bouncing";
  50713. },
  50714. enumerable: true,
  50715. configurable: true
  50716. });
  50717. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  50718. /**
  50719. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  50720. */
  50721. get: function () {
  50722. return this._autoTransitionRange;
  50723. },
  50724. /**
  50725. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  50726. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  50727. */
  50728. set: function (value) {
  50729. var _this = this;
  50730. if (this._autoTransitionRange === value) {
  50731. return;
  50732. }
  50733. this._autoTransitionRange = value;
  50734. var camera = this._attachedCamera;
  50735. if (value) {
  50736. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  50737. if (!mesh) {
  50738. return;
  50739. }
  50740. mesh.computeWorldMatrix(true);
  50741. var diagonal = mesh.getBoundingInfo().diagonalLength;
  50742. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  50743. _this.upperRadiusTransitionRange = diagonal * 0.05;
  50744. });
  50745. }
  50746. else if (this._onMeshTargetChangedObserver) {
  50747. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50748. }
  50749. },
  50750. enumerable: true,
  50751. configurable: true
  50752. });
  50753. BouncingBehavior.prototype.attach = function (camera) {
  50754. var _this = this;
  50755. this._attachedCamera = camera;
  50756. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50757. // Add the bounce animation to the lower radius limit
  50758. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  50759. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  50760. }
  50761. // Add the bounce animation to the upper radius limit
  50762. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  50763. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  50764. }
  50765. });
  50766. };
  50767. BouncingBehavior.prototype.detach = function () {
  50768. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50769. if (this._onMeshTargetChangedObserver) {
  50770. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  50771. }
  50772. this._attachedCamera = null;
  50773. };
  50774. /**
  50775. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  50776. * @param radiusLimit The limit to check against.
  50777. * @return Bool to indicate if at limit.
  50778. */
  50779. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  50780. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  50781. return true;
  50782. }
  50783. return false;
  50784. };
  50785. /**
  50786. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  50787. * @param radiusDelta The delta by which to animate to. Can be negative.
  50788. */
  50789. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  50790. var _this = this;
  50791. if (!this._radiusBounceTransition) {
  50792. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  50793. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  50794. }
  50795. // Prevent zoom until bounce has completed
  50796. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  50797. this._attachedCamera.wheelPrecision = Infinity;
  50798. this._attachedCamera.inertialRadiusOffset = 0;
  50799. // Animate to the radius limit
  50800. this.stopAllAnimations();
  50801. this._radiusIsAnimating = true;
  50802. 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(); }));
  50803. };
  50804. /**
  50805. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  50806. */
  50807. BouncingBehavior.prototype._clearAnimationLocks = function () {
  50808. this._radiusIsAnimating = false;
  50809. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  50810. };
  50811. /**
  50812. * Stops and removes all animations that have been applied to the camera
  50813. */
  50814. BouncingBehavior.prototype.stopAllAnimations = function () {
  50815. this._attachedCamera.animations = [];
  50816. while (this._animatables.length) {
  50817. this._animatables[0].onAnimationEnd = null;
  50818. this._animatables[0].stop();
  50819. this._animatables.shift();
  50820. }
  50821. };
  50822. /**
  50823. * The easing function used by animations
  50824. */
  50825. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  50826. /**
  50827. * The easing mode used by animations
  50828. */
  50829. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  50830. return BouncingBehavior;
  50831. }());
  50832. BABYLON.BouncingBehavior = BouncingBehavior;
  50833. })(BABYLON || (BABYLON = {}));
  50834. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  50835. var BABYLON;
  50836. (function (BABYLON) {
  50837. var AutoRotationBehavior = (function () {
  50838. function AutoRotationBehavior() {
  50839. this._zoomStopsAnimation = false;
  50840. this._idleRotationSpeed = 0.05;
  50841. this._idleRotationWaitTime = 2000;
  50842. this._idleRotationSpinupTime = 2000;
  50843. this._isPointerDown = false;
  50844. this._lastFrameTime = null;
  50845. this._lastInteractionTime = -Infinity;
  50846. this._cameraRotationSpeed = 0;
  50847. this._lastFrameRadius = 0;
  50848. }
  50849. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  50850. get: function () {
  50851. return "AutoRotation";
  50852. },
  50853. enumerable: true,
  50854. configurable: true
  50855. });
  50856. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  50857. /**
  50858. * Gets the flag that indicates if user zooming should stop animation.
  50859. */
  50860. get: function () {
  50861. return this._zoomStopsAnimation;
  50862. },
  50863. /**
  50864. * Sets the flag that indicates if user zooming should stop animation.
  50865. */
  50866. set: function (flag) {
  50867. this._zoomStopsAnimation = flag;
  50868. },
  50869. enumerable: true,
  50870. configurable: true
  50871. });
  50872. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  50873. /**
  50874. * Gets the default speed at which the camera rotates around the model.
  50875. */
  50876. get: function () {
  50877. return this._idleRotationSpeed;
  50878. },
  50879. /**
  50880. * Sets the default speed at which the camera rotates around the model.
  50881. */
  50882. set: function (speed) {
  50883. this._idleRotationSpeed = speed;
  50884. },
  50885. enumerable: true,
  50886. configurable: true
  50887. });
  50888. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  50889. /**
  50890. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  50891. */
  50892. get: function () {
  50893. return this._idleRotationWaitTime;
  50894. },
  50895. /**
  50896. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  50897. */
  50898. set: function (time) {
  50899. this._idleRotationWaitTime = time;
  50900. },
  50901. enumerable: true,
  50902. configurable: true
  50903. });
  50904. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  50905. /**
  50906. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  50907. */
  50908. get: function () {
  50909. return this._idleRotationSpinupTime;
  50910. },
  50911. /**
  50912. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  50913. */
  50914. set: function (time) {
  50915. this._idleRotationSpinupTime = time;
  50916. },
  50917. enumerable: true,
  50918. configurable: true
  50919. });
  50920. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  50921. /**
  50922. * Gets a value indicating if the camera is currently rotating because of this behavior
  50923. */
  50924. get: function () {
  50925. return Math.abs(this._cameraRotationSpeed) > 0;
  50926. },
  50927. enumerable: true,
  50928. configurable: true
  50929. });
  50930. AutoRotationBehavior.prototype.attach = function (camera) {
  50931. var _this = this;
  50932. this._attachedCamera = camera;
  50933. var scene = this._attachedCamera.getScene();
  50934. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  50935. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50936. _this._isPointerDown = true;
  50937. return;
  50938. }
  50939. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  50940. _this._isPointerDown = false;
  50941. }
  50942. });
  50943. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  50944. var now = BABYLON.Tools.Now;
  50945. var dt = 0;
  50946. if (_this._lastFrameTime != null) {
  50947. dt = now - _this._lastFrameTime;
  50948. }
  50949. _this._lastFrameTime = now;
  50950. // Stop the animation if there is user interaction and the animation should stop for this interaction
  50951. _this._applyUserInteraction();
  50952. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  50953. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  50954. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  50955. // Step camera rotation by rotation speed
  50956. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  50957. });
  50958. };
  50959. AutoRotationBehavior.prototype.detach = function () {
  50960. var scene = this._attachedCamera.getScene();
  50961. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  50962. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  50963. this._attachedCamera = null;
  50964. };
  50965. /**
  50966. * Returns true if user is scrolling.
  50967. * @return true if user is scrolling.
  50968. */
  50969. AutoRotationBehavior.prototype._userIsZooming = function () {
  50970. return this._attachedCamera.inertialRadiusOffset !== 0;
  50971. };
  50972. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  50973. var zoomHasHitLimit = false;
  50974. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  50975. zoomHasHitLimit = true;
  50976. }
  50977. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  50978. this._lastFrameRadius = this._attachedCamera.radius;
  50979. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  50980. };
  50981. /**
  50982. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  50983. */
  50984. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  50985. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  50986. this._lastInteractionTime = BABYLON.Tools.Now;
  50987. }
  50988. };
  50989. // Tools
  50990. AutoRotationBehavior.prototype._userIsMoving = function () {
  50991. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  50992. this._attachedCamera.inertialBetaOffset !== 0 ||
  50993. this._attachedCamera.inertialRadiusOffset !== 0 ||
  50994. this._attachedCamera.inertialPanningX !== 0 ||
  50995. this._attachedCamera.inertialPanningY !== 0 ||
  50996. this._isPointerDown;
  50997. };
  50998. return AutoRotationBehavior;
  50999. }());
  51000. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  51001. })(BABYLON || (BABYLON = {}));
  51002. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  51003. var BABYLON;
  51004. (function (BABYLON) {
  51005. var MorphTarget = (function () {
  51006. function MorphTarget(name, influence) {
  51007. if (influence === void 0) { influence = 0; }
  51008. this.name = name;
  51009. this.animations = new Array();
  51010. this.onInfluenceChanged = new BABYLON.Observable();
  51011. this.influence = influence;
  51012. }
  51013. Object.defineProperty(MorphTarget.prototype, "influence", {
  51014. get: function () {
  51015. return this._influence;
  51016. },
  51017. set: function (influence) {
  51018. if (this._influence === influence) {
  51019. return;
  51020. }
  51021. var previous = this._influence;
  51022. this._influence = influence;
  51023. if (this.onInfluenceChanged.hasObservers) {
  51024. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  51025. }
  51026. },
  51027. enumerable: true,
  51028. configurable: true
  51029. });
  51030. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  51031. get: function () {
  51032. return this._normals !== undefined;
  51033. },
  51034. enumerable: true,
  51035. configurable: true
  51036. });
  51037. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  51038. get: function () {
  51039. return this._tangents !== undefined;
  51040. },
  51041. enumerable: true,
  51042. configurable: true
  51043. });
  51044. MorphTarget.prototype.setPositions = function (data) {
  51045. this._positions = new Float32Array(data);
  51046. };
  51047. MorphTarget.prototype.getPositions = function () {
  51048. return this._positions;
  51049. };
  51050. MorphTarget.prototype.setNormals = function (data) {
  51051. this._normals = new Float32Array(data);
  51052. };
  51053. MorphTarget.prototype.getNormals = function () {
  51054. return this._normals;
  51055. };
  51056. MorphTarget.prototype.setTangents = function (data) {
  51057. this._tangents = new Float32Array(data);
  51058. };
  51059. MorphTarget.prototype.getTangents = function () {
  51060. return this._tangents;
  51061. };
  51062. /**
  51063. * Serializes the current target into a Serialization object.
  51064. * Returns the serialized object.
  51065. */
  51066. MorphTarget.prototype.serialize = function () {
  51067. var serializationObject = {};
  51068. serializationObject.name = this.name;
  51069. serializationObject.influence = this.influence;
  51070. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  51071. if (this.hasNormals) {
  51072. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  51073. }
  51074. if (this.hasTangents) {
  51075. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  51076. }
  51077. return serializationObject;
  51078. };
  51079. // Statics
  51080. MorphTarget.Parse = function (serializationObject) {
  51081. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  51082. result.setPositions(serializationObject.positions);
  51083. if (serializationObject.normals) {
  51084. result.setNormals(serializationObject.normals);
  51085. }
  51086. if (serializationObject.tangents) {
  51087. result.setTangents(serializationObject.tangents);
  51088. }
  51089. return result;
  51090. };
  51091. MorphTarget.FromMesh = function (mesh, name, influence) {
  51092. if (!name) {
  51093. name = mesh.name;
  51094. }
  51095. var result = new MorphTarget(name, influence);
  51096. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  51097. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  51098. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  51099. }
  51100. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  51101. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  51102. }
  51103. return result;
  51104. };
  51105. return MorphTarget;
  51106. }());
  51107. BABYLON.MorphTarget = MorphTarget;
  51108. })(BABYLON || (BABYLON = {}));
  51109. //# sourceMappingURL=babylon.morphTarget.js.map
  51110. var BABYLON;
  51111. (function (BABYLON) {
  51112. var MorphTargetManager = (function () {
  51113. function MorphTargetManager(scene) {
  51114. this._targets = new Array();
  51115. this._targetObservable = new Array();
  51116. this._activeTargets = new BABYLON.SmartArray(16);
  51117. this._supportsNormals = false;
  51118. this._supportsTangents = false;
  51119. this._vertexCount = 0;
  51120. this._uniqueId = 0;
  51121. this._tempInfluences = new Array();
  51122. if (!scene) {
  51123. scene = BABYLON.Engine.LastCreatedScene;
  51124. }
  51125. this._scene = scene;
  51126. this._scene.morphTargetManagers.push(this);
  51127. this._uniqueId = scene.getUniqueId();
  51128. }
  51129. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  51130. get: function () {
  51131. return this._uniqueId;
  51132. },
  51133. enumerable: true,
  51134. configurable: true
  51135. });
  51136. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  51137. get: function () {
  51138. return this._vertexCount;
  51139. },
  51140. enumerable: true,
  51141. configurable: true
  51142. });
  51143. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  51144. get: function () {
  51145. return this._supportsNormals;
  51146. },
  51147. enumerable: true,
  51148. configurable: true
  51149. });
  51150. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  51151. get: function () {
  51152. return this._supportsTangents;
  51153. },
  51154. enumerable: true,
  51155. configurable: true
  51156. });
  51157. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  51158. get: function () {
  51159. return this._targets.length;
  51160. },
  51161. enumerable: true,
  51162. configurable: true
  51163. });
  51164. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  51165. get: function () {
  51166. return this._activeTargets.length;
  51167. },
  51168. enumerable: true,
  51169. configurable: true
  51170. });
  51171. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  51172. get: function () {
  51173. return this._influences;
  51174. },
  51175. enumerable: true,
  51176. configurable: true
  51177. });
  51178. MorphTargetManager.prototype.getActiveTarget = function (index) {
  51179. return this._activeTargets.data[index];
  51180. };
  51181. MorphTargetManager.prototype.getTarget = function (index) {
  51182. return this._targets[index];
  51183. };
  51184. MorphTargetManager.prototype.addTarget = function (target) {
  51185. var _this = this;
  51186. if (this._vertexCount) {
  51187. if (this._vertexCount !== target.getPositions().length / 3) {
  51188. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  51189. return;
  51190. }
  51191. }
  51192. this._targets.push(target);
  51193. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  51194. _this._syncActiveTargets(needUpdate);
  51195. }));
  51196. this._syncActiveTargets(true);
  51197. };
  51198. MorphTargetManager.prototype.removeTarget = function (target) {
  51199. var index = this._targets.indexOf(target);
  51200. if (index >= 0) {
  51201. this._targets.splice(index, 1);
  51202. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  51203. this._vertexCount = 0;
  51204. this._syncActiveTargets(true);
  51205. }
  51206. };
  51207. /**
  51208. * Serializes the current manager into a Serialization object.
  51209. * Returns the serialized object.
  51210. */
  51211. MorphTargetManager.prototype.serialize = function () {
  51212. var serializationObject = {};
  51213. serializationObject.id = this.uniqueId;
  51214. serializationObject.targets = [];
  51215. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  51216. var target = _a[_i];
  51217. serializationObject.targets.push(target.serialize());
  51218. }
  51219. return serializationObject;
  51220. };
  51221. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  51222. this._syncActiveTargets(needUpdate);
  51223. };
  51224. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  51225. var influenceCount = 0;
  51226. this._activeTargets.reset();
  51227. this._supportsNormals = true;
  51228. this._supportsTangents = true;
  51229. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  51230. var target = _a[_i];
  51231. if (target.influence > 0) {
  51232. this._activeTargets.push(target);
  51233. this._tempInfluences[influenceCount++] = target.influence;
  51234. this._supportsNormals = this._supportsNormals && target.hasNormals;
  51235. this._supportsTangents = this._supportsTangents && target.hasTangents;
  51236. if (this._vertexCount === 0) {
  51237. this._vertexCount = target.getPositions().length / 3;
  51238. }
  51239. }
  51240. }
  51241. if (!this._influences || this._influences.length !== influenceCount) {
  51242. this._influences = new Float32Array(influenceCount);
  51243. }
  51244. for (var index = 0; index < influenceCount; index++) {
  51245. this._influences[index] = this._tempInfluences[index];
  51246. }
  51247. if (needUpdate) {
  51248. // Flag meshes as dirty to resync with the active targets
  51249. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  51250. var mesh = _c[_b];
  51251. if (mesh.morphTargetManager === this) {
  51252. mesh._syncGeometryWithMorphTargetManager();
  51253. }
  51254. }
  51255. }
  51256. };
  51257. // Statics
  51258. MorphTargetManager.Parse = function (serializationObject, scene) {
  51259. var result = new MorphTargetManager(scene);
  51260. result._uniqueId = serializationObject.id;
  51261. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  51262. var targetData = _a[_i];
  51263. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  51264. }
  51265. return result;
  51266. };
  51267. return MorphTargetManager;
  51268. }());
  51269. BABYLON.MorphTargetManager = MorphTargetManager;
  51270. })(BABYLON || (BABYLON = {}));
  51271. //# sourceMappingURL=babylon.morphTargetManager.js.map
  51272. 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}"};
  51273. 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};"};
  51274. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  51275. var BABYLON;
  51276. (function (BABYLON) {
  51277. var GridMaterialDefines = (function (_super) {
  51278. __extends(GridMaterialDefines, _super);
  51279. function GridMaterialDefines() {
  51280. var _this = _super.call(this) || this;
  51281. _this.TRANSPARENT = false;
  51282. _this.FOG = false;
  51283. _this.PREMULTIPLYALPHA = false;
  51284. _this.rebuild();
  51285. return _this;
  51286. }
  51287. return GridMaterialDefines;
  51288. }(BABYLON.MaterialDefines));
  51289. /**
  51290. * The grid materials allows you to wrap any shape with a grid.
  51291. * Colors are customizable.
  51292. */
  51293. var GridMaterial = (function (_super) {
  51294. __extends(GridMaterial, _super);
  51295. /**
  51296. * constructor
  51297. * @param name The name given to the material in order to identify it afterwards.
  51298. * @param scene The scene the material is used in.
  51299. */
  51300. function GridMaterial(name, scene) {
  51301. var _this = _super.call(this, name, scene) || this;
  51302. /**
  51303. * Main color of the grid (e.g. between lines)
  51304. */
  51305. _this.mainColor = BABYLON.Color3.Black();
  51306. /**
  51307. * Color of the grid lines.
  51308. */
  51309. _this.lineColor = BABYLON.Color3.Teal();
  51310. /**
  51311. * The scale of the grid compared to unit.
  51312. */
  51313. _this.gridRatio = 1.0;
  51314. /**
  51315. * The frequency of thicker lines.
  51316. */
  51317. _this.majorUnitFrequency = 10;
  51318. /**
  51319. * The visibility of minor units in the grid.
  51320. */
  51321. _this.minorUnitVisibility = 0.33;
  51322. /**
  51323. * The grid opacity outside of the lines.
  51324. */
  51325. _this.opacity = 1.0;
  51326. /**
  51327. * Determine RBG output is premultiplied by alpha value.
  51328. */
  51329. _this.preMultiplyAlpha = false;
  51330. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  51331. return _this;
  51332. }
  51333. /**
  51334. * Returns wehter or not the grid requires alpha blending.
  51335. */
  51336. GridMaterial.prototype.needAlphaBlending = function () {
  51337. return this.opacity < 1.0;
  51338. };
  51339. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  51340. if (this.isFrozen) {
  51341. if (this._wasPreviouslyReady && subMesh.effect) {
  51342. return true;
  51343. }
  51344. }
  51345. if (!subMesh._materialDefines) {
  51346. subMesh._materialDefines = new GridMaterialDefines();
  51347. }
  51348. var defines = subMesh._materialDefines;
  51349. var scene = this.getScene();
  51350. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  51351. if (this._renderId === scene.getRenderId()) {
  51352. return true;
  51353. }
  51354. }
  51355. var engine = scene.getEngine();
  51356. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  51357. defines.TRANSPARENT = !defines.TRANSPARENT;
  51358. defines.markAsUnprocessed();
  51359. }
  51360. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  51361. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  51362. defines.markAsUnprocessed();
  51363. }
  51364. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  51365. // Get correct effect
  51366. if (defines.isDirty) {
  51367. defines.markAsProcessed();
  51368. scene.resetCachedMaterial();
  51369. // Attributes
  51370. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  51371. // Defines
  51372. var join = defines.toString();
  51373. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "vFogInfos", "vFogColor", "world", "view"], [], join, null, this.onCompiled, this.onError), defines);
  51374. }
  51375. if (!subMesh.effect.isReady()) {
  51376. return false;
  51377. }
  51378. this._renderId = scene.getRenderId();
  51379. this._wasPreviouslyReady = true;
  51380. return true;
  51381. };
  51382. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  51383. var scene = this.getScene();
  51384. var defines = subMesh._materialDefines;
  51385. if (!defines) {
  51386. return;
  51387. }
  51388. var effect = subMesh.effect;
  51389. this._activeEffect = effect;
  51390. // Matrices
  51391. this.bindOnlyWorldMatrix(world);
  51392. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  51393. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  51394. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  51395. // Uniforms
  51396. if (this._mustRebind(scene, effect)) {
  51397. this._activeEffect.setColor3("mainColor", this.mainColor);
  51398. this._activeEffect.setColor3("lineColor", this.lineColor);
  51399. this._gridControl.x = this.gridRatio;
  51400. this._gridControl.y = Math.round(this.majorUnitFrequency);
  51401. this._gridControl.z = this.minorUnitVisibility;
  51402. this._gridControl.w = this.opacity;
  51403. this._activeEffect.setVector4("gridControl", this._gridControl);
  51404. }
  51405. // Fog
  51406. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  51407. this._afterBind(mesh, this._activeEffect);
  51408. };
  51409. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  51410. _super.prototype.dispose.call(this, forceDisposeEffect);
  51411. };
  51412. GridMaterial.prototype.clone = function (name) {
  51413. var _this = this;
  51414. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  51415. };
  51416. GridMaterial.prototype.serialize = function () {
  51417. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51418. serializationObject.customType = "BABYLON.GridMaterial";
  51419. return serializationObject;
  51420. };
  51421. GridMaterial.prototype.getClassName = function () {
  51422. return "GridMaterial";
  51423. };
  51424. GridMaterial.Parse = function (source, scene, rootUrl) {
  51425. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  51426. };
  51427. __decorate([
  51428. BABYLON.serializeAsColor3()
  51429. ], GridMaterial.prototype, "mainColor", void 0);
  51430. __decorate([
  51431. BABYLON.serializeAsColor3()
  51432. ], GridMaterial.prototype, "lineColor", void 0);
  51433. __decorate([
  51434. BABYLON.serialize()
  51435. ], GridMaterial.prototype, "gridRatio", void 0);
  51436. __decorate([
  51437. BABYLON.serialize()
  51438. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  51439. __decorate([
  51440. BABYLON.serialize()
  51441. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  51442. __decorate([
  51443. BABYLON.serialize()
  51444. ], GridMaterial.prototype, "opacity", void 0);
  51445. __decorate([
  51446. BABYLON.serialize()
  51447. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  51448. return GridMaterial;
  51449. }(BABYLON.PushMaterial));
  51450. BABYLON.GridMaterial = GridMaterial;
  51451. })(BABYLON || (BABYLON = {}));
  51452. //# sourceMappingURL=babylon.gridmaterial.js.map
  51453. 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}";
  51454. 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}";
  51455. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  51456. var BABYLON;
  51457. (function (BABYLON) {
  51458. var GLTFLoaderCoordinateSystemMode;
  51459. (function (GLTFLoaderCoordinateSystemMode) {
  51460. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  51461. // 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.
  51462. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  51463. // The glTF right-handed data is not transformed in any form and is loaded directly.
  51464. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  51465. // Sets the useRightHandedSystem flag on the scene.
  51466. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  51467. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  51468. var GLTFFileLoader = (function () {
  51469. function GLTFFileLoader() {
  51470. // V2 options
  51471. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  51472. this.name = "gltf";
  51473. this.extensions = {
  51474. ".gltf": { isBinary: false },
  51475. ".glb": { isBinary: true }
  51476. };
  51477. }
  51478. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  51479. var loaderData = GLTFFileLoader._parse(data, onError);
  51480. if (!loaderData) {
  51481. return;
  51482. }
  51483. var loader = this._getLoader(loaderData, onError);
  51484. if (!loader) {
  51485. return;
  51486. }
  51487. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  51488. };
  51489. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  51490. var loaderData = GLTFFileLoader._parse(data, onError);
  51491. if (!loaderData) {
  51492. return;
  51493. }
  51494. var loader = this._getLoader(loaderData, onError);
  51495. if (!loader) {
  51496. return;
  51497. }
  51498. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  51499. };
  51500. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  51501. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  51502. };
  51503. GLTFFileLoader._parse = function (data, onError) {
  51504. if (data instanceof ArrayBuffer) {
  51505. return GLTFFileLoader._parseBinary(data, onError);
  51506. }
  51507. try {
  51508. return {
  51509. json: JSON.parse(data),
  51510. bin: null
  51511. };
  51512. }
  51513. catch (e) {
  51514. onError(e.message);
  51515. return null;
  51516. }
  51517. };
  51518. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  51519. var loaderVersion = { major: 2, minor: 0 };
  51520. var asset = loaderData.json.asset || {};
  51521. var version = GLTFFileLoader._parseVersion(asset.version);
  51522. if (!version) {
  51523. onError("Invalid version: " + asset.version);
  51524. return null;
  51525. }
  51526. if (asset.minVersion !== undefined) {
  51527. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  51528. if (!minVersion) {
  51529. onError("Invalid minimum version: " + asset.minVersion);
  51530. return null;
  51531. }
  51532. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  51533. onError("Incompatible minimum version: " + asset.minVersion);
  51534. return null;
  51535. }
  51536. }
  51537. var createLoaders = {
  51538. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  51539. 2: GLTFFileLoader.CreateGLTFLoaderV2
  51540. };
  51541. var createLoader = createLoaders[version.major];
  51542. if (!createLoader) {
  51543. onError("Unsupported version: " + asset.version);
  51544. return null;
  51545. }
  51546. return createLoader(this);
  51547. };
  51548. GLTFFileLoader._parseBinary = function (data, onError) {
  51549. var Binary = {
  51550. Magic: 0x46546C67
  51551. };
  51552. var binaryReader = new BinaryReader(data);
  51553. var magic = binaryReader.readUint32();
  51554. if (magic !== Binary.Magic) {
  51555. onError("Unexpected magic: " + magic);
  51556. return null;
  51557. }
  51558. var version = binaryReader.readUint32();
  51559. switch (version) {
  51560. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  51561. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  51562. }
  51563. onError("Unsupported version: " + version);
  51564. return null;
  51565. };
  51566. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  51567. var ContentFormat = {
  51568. JSON: 0
  51569. };
  51570. var length = binaryReader.readUint32();
  51571. if (length != binaryReader.getLength()) {
  51572. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  51573. return null;
  51574. }
  51575. var contentLength = binaryReader.readUint32();
  51576. var contentFormat = binaryReader.readUint32();
  51577. var content;
  51578. switch (contentFormat) {
  51579. case ContentFormat.JSON:
  51580. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  51581. break;
  51582. default:
  51583. onError("Unexpected content format: " + contentFormat);
  51584. return null;
  51585. }
  51586. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  51587. var body = binaryReader.readUint8Array(bytesRemaining);
  51588. return {
  51589. json: content,
  51590. bin: body
  51591. };
  51592. };
  51593. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  51594. var ChunkFormat = {
  51595. JSON: 0x4E4F534A,
  51596. BIN: 0x004E4942
  51597. };
  51598. var length = binaryReader.readUint32();
  51599. if (length !== binaryReader.getLength()) {
  51600. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  51601. return null;
  51602. }
  51603. // JSON chunk
  51604. var chunkLength = binaryReader.readUint32();
  51605. var chunkFormat = binaryReader.readUint32();
  51606. if (chunkFormat !== ChunkFormat.JSON) {
  51607. onError("First chunk format is not JSON");
  51608. return null;
  51609. }
  51610. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  51611. // Look for BIN chunk
  51612. var bin = null;
  51613. while (binaryReader.getPosition() < binaryReader.getLength()) {
  51614. chunkLength = binaryReader.readUint32();
  51615. chunkFormat = binaryReader.readUint32();
  51616. switch (chunkFormat) {
  51617. case ChunkFormat.JSON:
  51618. onError("Unexpected JSON chunk");
  51619. return null;
  51620. case ChunkFormat.BIN:
  51621. bin = binaryReader.readUint8Array(chunkLength);
  51622. break;
  51623. default:
  51624. // ignore unrecognized chunkFormat
  51625. binaryReader.skipBytes(chunkLength);
  51626. break;
  51627. }
  51628. }
  51629. return {
  51630. json: json,
  51631. bin: bin
  51632. };
  51633. };
  51634. GLTFFileLoader._parseVersion = function (version) {
  51635. if (!version) {
  51636. return null;
  51637. }
  51638. var parts = version.split(".");
  51639. if (parts.length != 2) {
  51640. return null;
  51641. }
  51642. var major = +parts[0];
  51643. if (isNaN(major)) {
  51644. return null;
  51645. }
  51646. var minor = +parts[1];
  51647. if (isNaN(minor)) {
  51648. return null;
  51649. }
  51650. return {
  51651. major: major,
  51652. minor: minor
  51653. };
  51654. };
  51655. GLTFFileLoader._compareVersion = function (a, b) {
  51656. if (a.major > b.major)
  51657. return 1;
  51658. if (a.major < b.major)
  51659. return -1;
  51660. if (a.minor > b.minor)
  51661. return 1;
  51662. if (a.minor < b.minor)
  51663. return -1;
  51664. return 0;
  51665. };
  51666. GLTFFileLoader._decodeBufferToText = function (view) {
  51667. var result = "";
  51668. var length = view.byteLength;
  51669. for (var i = 0; i < length; ++i) {
  51670. result += String.fromCharCode(view[i]);
  51671. }
  51672. return result;
  51673. };
  51674. // V1 options
  51675. GLTFFileLoader.HomogeneousCoordinates = false;
  51676. GLTFFileLoader.IncrementalLoading = true;
  51677. return GLTFFileLoader;
  51678. }());
  51679. BABYLON.GLTFFileLoader = GLTFFileLoader;
  51680. var BinaryReader = (function () {
  51681. function BinaryReader(arrayBuffer) {
  51682. this._arrayBuffer = arrayBuffer;
  51683. this._dataView = new DataView(arrayBuffer);
  51684. this._byteOffset = 0;
  51685. }
  51686. BinaryReader.prototype.getPosition = function () {
  51687. return this._byteOffset;
  51688. };
  51689. BinaryReader.prototype.getLength = function () {
  51690. return this._arrayBuffer.byteLength;
  51691. };
  51692. BinaryReader.prototype.readUint32 = function () {
  51693. var value = this._dataView.getUint32(this._byteOffset, true);
  51694. this._byteOffset += 4;
  51695. return value;
  51696. };
  51697. BinaryReader.prototype.readUint8Array = function (length) {
  51698. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  51699. this._byteOffset += length;
  51700. return value;
  51701. };
  51702. BinaryReader.prototype.skipBytes = function (length) {
  51703. this._byteOffset += length;
  51704. };
  51705. return BinaryReader;
  51706. }());
  51707. if (BABYLON.SceneLoader) {
  51708. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  51709. }
  51710. })(BABYLON || (BABYLON = {}));
  51711. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  51712. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  51713. var BABYLON;
  51714. (function (BABYLON) {
  51715. var GLTF1;
  51716. (function (GLTF1) {
  51717. /**
  51718. * Enums
  51719. */
  51720. var EComponentType;
  51721. (function (EComponentType) {
  51722. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  51723. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  51724. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  51725. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  51726. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  51727. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  51728. var EShaderType;
  51729. (function (EShaderType) {
  51730. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  51731. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  51732. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  51733. var EParameterType;
  51734. (function (EParameterType) {
  51735. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  51736. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  51737. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  51738. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  51739. EParameterType[EParameterType["INT"] = 5124] = "INT";
  51740. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  51741. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  51742. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  51743. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  51744. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  51745. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  51746. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  51747. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  51748. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  51749. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  51750. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  51751. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  51752. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  51753. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  51754. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  51755. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  51756. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  51757. var ETextureWrapMode;
  51758. (function (ETextureWrapMode) {
  51759. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  51760. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  51761. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  51762. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  51763. var ETextureFilterType;
  51764. (function (ETextureFilterType) {
  51765. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  51766. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  51767. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  51768. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  51769. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  51770. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  51771. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  51772. var ETextureFormat;
  51773. (function (ETextureFormat) {
  51774. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  51775. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  51776. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  51777. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  51778. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  51779. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  51780. var ECullingType;
  51781. (function (ECullingType) {
  51782. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  51783. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  51784. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  51785. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  51786. var EBlendingFunction;
  51787. (function (EBlendingFunction) {
  51788. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  51789. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  51790. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  51791. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  51792. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  51793. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  51794. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  51795. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  51796. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  51797. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  51798. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  51799. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  51800. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  51801. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  51802. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  51803. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  51804. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  51805. })(BABYLON || (BABYLON = {}));
  51806. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  51807. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  51808. var BABYLON;
  51809. (function (BABYLON) {
  51810. var GLTF1;
  51811. (function (GLTF1) {
  51812. /**
  51813. * Tokenizer. Used for shaders compatibility
  51814. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  51815. */
  51816. var ETokenType;
  51817. (function (ETokenType) {
  51818. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  51819. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  51820. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  51821. })(ETokenType || (ETokenType = {}));
  51822. var Tokenizer = (function () {
  51823. function Tokenizer(toParse) {
  51824. this._pos = 0;
  51825. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  51826. this._toParse = toParse;
  51827. this._maxPos = toParse.length;
  51828. }
  51829. Tokenizer.prototype.getNextToken = function () {
  51830. if (this.isEnd())
  51831. return ETokenType.END_OF_INPUT;
  51832. this.currentString = this.read();
  51833. this.currentToken = ETokenType.UNKNOWN;
  51834. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  51835. this.currentToken = ETokenType.IDENTIFIER;
  51836. this.currentIdentifier = this.currentString;
  51837. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  51838. this.currentIdentifier += this.currentString;
  51839. this.forward();
  51840. }
  51841. }
  51842. return this.currentToken;
  51843. };
  51844. Tokenizer.prototype.peek = function () {
  51845. return this._toParse[this._pos];
  51846. };
  51847. Tokenizer.prototype.read = function () {
  51848. return this._toParse[this._pos++];
  51849. };
  51850. Tokenizer.prototype.forward = function () {
  51851. this._pos++;
  51852. };
  51853. Tokenizer.prototype.isEnd = function () {
  51854. return this._pos >= this._maxPos;
  51855. };
  51856. return Tokenizer;
  51857. }());
  51858. /**
  51859. * Values
  51860. */
  51861. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  51862. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  51863. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  51864. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  51865. /**
  51866. * Parse
  51867. */
  51868. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  51869. for (var buf in parsedBuffers) {
  51870. var parsedBuffer = parsedBuffers[buf];
  51871. gltfRuntime.buffers[buf] = parsedBuffer;
  51872. gltfRuntime.buffersCount++;
  51873. }
  51874. };
  51875. var parseShaders = function (parsedShaders, gltfRuntime) {
  51876. for (var sha in parsedShaders) {
  51877. var parsedShader = parsedShaders[sha];
  51878. gltfRuntime.shaders[sha] = parsedShader;
  51879. gltfRuntime.shaderscount++;
  51880. }
  51881. };
  51882. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  51883. for (var object in parsedObjects) {
  51884. var parsedObject = parsedObjects[object];
  51885. gltfRuntime[runtimeProperty][object] = parsedObject;
  51886. }
  51887. };
  51888. /**
  51889. * Utils
  51890. */
  51891. var normalizeUVs = function (buffer) {
  51892. if (!buffer) {
  51893. return;
  51894. }
  51895. for (var i = 0; i < buffer.length / 2; i++) {
  51896. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  51897. }
  51898. };
  51899. var replaceInString = function (str, searchValue, replaceValue) {
  51900. while (str.indexOf(searchValue) !== -1) {
  51901. str = str.replace(searchValue, replaceValue);
  51902. }
  51903. return str;
  51904. };
  51905. var getAttribute = function (attributeParameter) {
  51906. if (attributeParameter.semantic === "NORMAL") {
  51907. return "normal";
  51908. }
  51909. else if (attributeParameter.semantic === "POSITION") {
  51910. return "position";
  51911. }
  51912. else if (attributeParameter.semantic === "JOINT") {
  51913. return "matricesIndices";
  51914. }
  51915. else if (attributeParameter.semantic === "WEIGHT") {
  51916. return "matricesWeights";
  51917. }
  51918. else if (attributeParameter.semantic === "COLOR") {
  51919. return "color";
  51920. }
  51921. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  51922. var channel = Number(attributeParameter.semantic.split("_")[1]);
  51923. return "uv" + (channel === 0 ? "" : channel + 1);
  51924. }
  51925. };
  51926. /**
  51927. * Returns the animation path (glTF -> Babylon)
  51928. */
  51929. var getAnimationPath = function (path) {
  51930. var index = glTFAnimationPaths.indexOf(path);
  51931. if (index !== -1) {
  51932. return babylonAnimationPaths[index];
  51933. }
  51934. return path;
  51935. };
  51936. /**
  51937. * Loads and creates animations
  51938. */
  51939. var loadAnimations = function (gltfRuntime) {
  51940. for (var anim in gltfRuntime.animations) {
  51941. var animation = gltfRuntime.animations[anim];
  51942. var lastAnimation = null;
  51943. for (var i = 0; i < animation.channels.length; i++) {
  51944. // Get parameters and load buffers
  51945. var channel = animation.channels[i];
  51946. var sampler = animation.samplers[channel.sampler];
  51947. if (!sampler) {
  51948. continue;
  51949. }
  51950. var inputData = null;
  51951. var outputData = null;
  51952. if (animation.parameters) {
  51953. inputData = animation.parameters[sampler.input];
  51954. outputData = animation.parameters[sampler.output];
  51955. }
  51956. else {
  51957. inputData = sampler.input;
  51958. outputData = sampler.output;
  51959. }
  51960. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  51961. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  51962. var targetID = channel.target.id;
  51963. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  51964. if (targetNode === null) {
  51965. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  51966. }
  51967. if (targetNode === null) {
  51968. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  51969. continue;
  51970. }
  51971. var isBone = targetNode instanceof BABYLON.Bone;
  51972. // Get target path (position, rotation or scaling)
  51973. var targetPath = channel.target.path;
  51974. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  51975. if (targetPathIndex !== -1) {
  51976. targetPath = babylonAnimationPaths[targetPathIndex];
  51977. }
  51978. // Determine animation type
  51979. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  51980. if (!isBone) {
  51981. if (targetPath === "rotationQuaternion") {
  51982. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  51983. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  51984. }
  51985. else {
  51986. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  51987. }
  51988. }
  51989. // Create animation and key frames
  51990. var babylonAnimation = null;
  51991. var keys = [];
  51992. var arrayOffset = 0;
  51993. var modifyKey = false;
  51994. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  51995. babylonAnimation = lastAnimation;
  51996. modifyKey = true;
  51997. }
  51998. if (!modifyKey) {
  51999. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52000. }
  52001. // For each frame
  52002. for (var j = 0; j < bufferInput.length; j++) {
  52003. var value = null;
  52004. if (targetPath === "rotationQuaternion") {
  52005. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  52006. arrayOffset += 4;
  52007. }
  52008. else {
  52009. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  52010. arrayOffset += 3;
  52011. }
  52012. if (isBone) {
  52013. var bone = targetNode;
  52014. var translation = BABYLON.Vector3.Zero();
  52015. var rotationQuaternion = new BABYLON.Quaternion();
  52016. var scaling = BABYLON.Vector3.Zero();
  52017. // Warning on decompose
  52018. var mat = bone.getBaseMatrix();
  52019. if (modifyKey) {
  52020. mat = lastAnimation.getKeys()[j].value;
  52021. }
  52022. mat.decompose(scaling, rotationQuaternion, translation);
  52023. if (targetPath === "position") {
  52024. translation = value;
  52025. }
  52026. else if (targetPath === "rotationQuaternion") {
  52027. rotationQuaternion = value;
  52028. }
  52029. else {
  52030. scaling = value;
  52031. }
  52032. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  52033. }
  52034. if (!modifyKey) {
  52035. keys.push({
  52036. frame: bufferInput[j],
  52037. value: value
  52038. });
  52039. }
  52040. else {
  52041. lastAnimation.getKeys()[j].value = value;
  52042. }
  52043. }
  52044. // Finish
  52045. if (!modifyKey) {
  52046. babylonAnimation.setKeys(keys);
  52047. targetNode.animations.push(babylonAnimation);
  52048. }
  52049. lastAnimation = babylonAnimation;
  52050. gltfRuntime.scene.stopAnimation(targetNode);
  52051. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  52052. }
  52053. }
  52054. };
  52055. /**
  52056. * Returns the bones transformation matrix
  52057. */
  52058. var configureBoneTransformation = function (node) {
  52059. var mat = null;
  52060. if (node.translation || node.rotation || node.scale) {
  52061. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  52062. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  52063. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  52064. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  52065. }
  52066. else {
  52067. mat = BABYLON.Matrix.FromArray(node.matrix);
  52068. }
  52069. return mat;
  52070. };
  52071. /**
  52072. * Returns the parent bone
  52073. */
  52074. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  52075. // Try to find
  52076. for (var i = 0; i < newSkeleton.bones.length; i++) {
  52077. if (newSkeleton.bones[i].name === jointName) {
  52078. return newSkeleton.bones[i];
  52079. }
  52080. }
  52081. // Not found, search in gltf nodes
  52082. var nodes = gltfRuntime.nodes;
  52083. for (var nde in nodes) {
  52084. var node = nodes[nde];
  52085. if (!node.jointName) {
  52086. continue;
  52087. }
  52088. var children = node.children;
  52089. for (var i = 0; i < children.length; i++) {
  52090. var child = gltfRuntime.nodes[children[i]];
  52091. if (!child.jointName) {
  52092. continue;
  52093. }
  52094. if (child.jointName === jointName) {
  52095. var mat = configureBoneTransformation(node);
  52096. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  52097. bone.id = nde;
  52098. return bone;
  52099. }
  52100. }
  52101. }
  52102. return null;
  52103. };
  52104. /**
  52105. * Returns the appropriate root node
  52106. */
  52107. var getNodeToRoot = function (nodesToRoot, id) {
  52108. for (var i = 0; i < nodesToRoot.length; i++) {
  52109. var nodeToRoot = nodesToRoot[i];
  52110. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  52111. var child = nodeToRoot.node.children[j];
  52112. if (child === id) {
  52113. return nodeToRoot.bone;
  52114. }
  52115. }
  52116. }
  52117. return null;
  52118. };
  52119. /**
  52120. * Returns the node with the joint name
  52121. */
  52122. var getJointNode = function (gltfRuntime, jointName) {
  52123. var nodes = gltfRuntime.nodes;
  52124. var node = nodes[jointName];
  52125. if (node) {
  52126. return {
  52127. node: node,
  52128. id: jointName
  52129. };
  52130. }
  52131. for (var nde in nodes) {
  52132. node = nodes[nde];
  52133. if (node.jointName === jointName) {
  52134. return {
  52135. node: node,
  52136. id: nde
  52137. };
  52138. }
  52139. }
  52140. return null;
  52141. };
  52142. /**
  52143. * Checks if a nodes is in joints
  52144. */
  52145. var nodeIsInJoints = function (skins, id) {
  52146. for (var i = 0; i < skins.jointNames.length; i++) {
  52147. if (skins.jointNames[i] === id) {
  52148. return true;
  52149. }
  52150. }
  52151. return false;
  52152. };
  52153. /**
  52154. * Fills the nodes to root for bones and builds hierarchy
  52155. */
  52156. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  52157. // Creates nodes for root
  52158. for (var nde in gltfRuntime.nodes) {
  52159. var node = gltfRuntime.nodes[nde];
  52160. var id = nde;
  52161. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  52162. continue;
  52163. }
  52164. // Create node to root bone
  52165. var mat = configureBoneTransformation(node);
  52166. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  52167. bone.id = id;
  52168. nodesToRoot.push({ bone: bone, node: node, id: id });
  52169. }
  52170. // Parenting
  52171. for (var i = 0; i < nodesToRoot.length; i++) {
  52172. var nodeToRoot = nodesToRoot[i];
  52173. var children = nodeToRoot.node.children;
  52174. for (var j = 0; j < children.length; j++) {
  52175. var child = null;
  52176. for (var k = 0; k < nodesToRoot.length; k++) {
  52177. if (nodesToRoot[k].id === children[j]) {
  52178. child = nodesToRoot[k];
  52179. break;
  52180. }
  52181. }
  52182. if (child) {
  52183. child.bone._parent = nodeToRoot.bone;
  52184. nodeToRoot.bone.children.push(child.bone);
  52185. }
  52186. }
  52187. }
  52188. };
  52189. var printMat = function (m) {
  52190. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  52191. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  52192. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  52193. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  52194. };
  52195. /**
  52196. * Imports a skeleton
  52197. */
  52198. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  52199. if (!newSkeleton) {
  52200. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  52201. }
  52202. if (!skins.babylonSkeleton) {
  52203. return newSkeleton;
  52204. }
  52205. // Matrices
  52206. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  52207. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52208. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  52209. // Find the root bones
  52210. var nodesToRoot = [];
  52211. var nodesToRootToAdd = [];
  52212. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  52213. newSkeleton.bones = [];
  52214. // Joints
  52215. for (var i = 0; i < skins.jointNames.length; i++) {
  52216. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  52217. var node = jointNode.node;
  52218. if (!node) {
  52219. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  52220. continue;
  52221. }
  52222. var id = jointNode.id;
  52223. // Optimize, if the bone already exists...
  52224. var existingBone = gltfRuntime.scene.getBoneByID(id);
  52225. if (existingBone) {
  52226. newSkeleton.bones.push(existingBone);
  52227. continue;
  52228. }
  52229. // Search for parent bone
  52230. var foundBone = false;
  52231. var parentBone = null;
  52232. for (var j = 0; j < i; j++) {
  52233. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  52234. if (!joint) {
  52235. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  52236. continue;
  52237. }
  52238. var children = joint.children;
  52239. if (!children) {
  52240. continue;
  52241. }
  52242. foundBone = false;
  52243. for (var k = 0; k < children.length; k++) {
  52244. if (children[k] === id) {
  52245. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  52246. foundBone = true;
  52247. break;
  52248. }
  52249. }
  52250. if (foundBone) {
  52251. break;
  52252. }
  52253. }
  52254. // Create bone
  52255. var mat = configureBoneTransformation(node);
  52256. if (!parentBone && nodesToRoot.length > 0) {
  52257. parentBone = getNodeToRoot(nodesToRoot, id);
  52258. if (parentBone) {
  52259. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  52260. nodesToRootToAdd.push(parentBone);
  52261. }
  52262. }
  52263. }
  52264. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  52265. bone.id = id;
  52266. }
  52267. // Polish
  52268. var bones = newSkeleton.bones;
  52269. newSkeleton.bones = [];
  52270. for (var i = 0; i < skins.jointNames.length; i++) {
  52271. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  52272. if (!jointNode) {
  52273. continue;
  52274. }
  52275. for (var j = 0; j < bones.length; j++) {
  52276. if (bones[j].id === jointNode.id) {
  52277. newSkeleton.bones.push(bones[j]);
  52278. break;
  52279. }
  52280. }
  52281. }
  52282. newSkeleton.prepare();
  52283. // Finish
  52284. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  52285. newSkeleton.bones.push(nodesToRootToAdd[i]);
  52286. }
  52287. return newSkeleton;
  52288. };
  52289. /**
  52290. * Imports a mesh and its geometries
  52291. */
  52292. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  52293. if (!newMesh) {
  52294. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  52295. newMesh.id = id;
  52296. }
  52297. if (!node.babylonNode) {
  52298. return newMesh;
  52299. }
  52300. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  52301. if (!newMesh.material) {
  52302. newMesh.material = multiMat;
  52303. }
  52304. var vertexData = new BABYLON.VertexData();
  52305. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  52306. var verticesStarts = [];
  52307. var verticesCounts = [];
  52308. var indexStarts = [];
  52309. var indexCounts = [];
  52310. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  52311. var meshID = meshes[meshIndex];
  52312. var mesh = gltfRuntime.meshes[meshID];
  52313. if (!mesh) {
  52314. continue;
  52315. }
  52316. // Positions, normals and UVs
  52317. for (var i = 0; i < mesh.primitives.length; i++) {
  52318. // Temporary vertex data
  52319. var tempVertexData = new BABYLON.VertexData();
  52320. var primitive = mesh.primitives[i];
  52321. if (primitive.mode !== 4) {
  52322. // continue;
  52323. }
  52324. var attributes = primitive.attributes;
  52325. var accessor = null;
  52326. var buffer = null;
  52327. // Set positions, normal and uvs
  52328. for (var semantic in attributes) {
  52329. // Link accessor and buffer view
  52330. accessor = gltfRuntime.accessors[attributes[semantic]];
  52331. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52332. if (semantic === "NORMAL") {
  52333. tempVertexData.normals = new Float32Array(buffer.length);
  52334. tempVertexData.normals.set(buffer);
  52335. }
  52336. else if (semantic === "POSITION") {
  52337. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  52338. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  52339. for (var j = 0; j < buffer.length; j += 4) {
  52340. tempVertexData.positions[j] = buffer[j];
  52341. tempVertexData.positions[j + 1] = buffer[j + 1];
  52342. tempVertexData.positions[j + 2] = buffer[j + 2];
  52343. }
  52344. }
  52345. else {
  52346. tempVertexData.positions = new Float32Array(buffer.length);
  52347. tempVertexData.positions.set(buffer);
  52348. }
  52349. verticesCounts.push(tempVertexData.positions.length);
  52350. }
  52351. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  52352. var channel = Number(semantic.split("_")[1]);
  52353. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  52354. var uvs = new Float32Array(buffer.length);
  52355. uvs.set(buffer);
  52356. normalizeUVs(uvs);
  52357. tempVertexData.set(uvs, uvKind);
  52358. }
  52359. else if (semantic === "JOINT") {
  52360. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  52361. tempVertexData.matricesIndices.set(buffer);
  52362. }
  52363. else if (semantic === "WEIGHT") {
  52364. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  52365. tempVertexData.matricesWeights.set(buffer);
  52366. }
  52367. else if (semantic === "COLOR") {
  52368. tempVertexData.colors = new Float32Array(buffer.length);
  52369. tempVertexData.colors.set(buffer);
  52370. }
  52371. }
  52372. // Indices
  52373. accessor = gltfRuntime.accessors[primitive.indices];
  52374. if (accessor) {
  52375. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  52376. tempVertexData.indices = new Int32Array(buffer.length);
  52377. tempVertexData.indices.set(buffer);
  52378. indexCounts.push(tempVertexData.indices.length);
  52379. }
  52380. else {
  52381. // Set indices on the fly
  52382. var indices = [];
  52383. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  52384. indices.push(j);
  52385. }
  52386. tempVertexData.indices = new Int32Array(indices);
  52387. indexCounts.push(tempVertexData.indices.length);
  52388. }
  52389. vertexData.merge(tempVertexData);
  52390. tempVertexData = undefined;
  52391. // Sub material
  52392. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  52393. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  52394. // Update vertices start and index start
  52395. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  52396. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  52397. }
  52398. }
  52399. // Apply geometry
  52400. geometry.setAllVerticesData(vertexData, false);
  52401. newMesh.computeWorldMatrix(true);
  52402. // Apply submeshes
  52403. newMesh.subMeshes = [];
  52404. var index = 0;
  52405. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  52406. var meshID = meshes[meshIndex];
  52407. var mesh = gltfRuntime.meshes[meshID];
  52408. if (!mesh) {
  52409. continue;
  52410. }
  52411. for (var i = 0; i < mesh.primitives.length; i++) {
  52412. if (mesh.primitives[i].mode !== 4) {
  52413. //continue;
  52414. }
  52415. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  52416. index++;
  52417. }
  52418. }
  52419. // Finish
  52420. return newMesh;
  52421. };
  52422. /**
  52423. * Configure node transformation from position, rotation and scaling
  52424. */
  52425. var configureNode = function (newNode, position, rotation, scaling) {
  52426. if (newNode.position) {
  52427. newNode.position = position;
  52428. }
  52429. if (newNode.rotationQuaternion || newNode.rotation) {
  52430. newNode.rotationQuaternion = rotation;
  52431. }
  52432. if (newNode.scaling) {
  52433. newNode.scaling = scaling;
  52434. }
  52435. };
  52436. /**
  52437. * Configures node from transformation matrix
  52438. */
  52439. var configureNodeFromMatrix = function (newNode, node, parent) {
  52440. if (node.matrix) {
  52441. var position = new BABYLON.Vector3(0, 0, 0);
  52442. var rotation = new BABYLON.Quaternion();
  52443. var scaling = new BABYLON.Vector3(0, 0, 0);
  52444. var mat = BABYLON.Matrix.FromArray(node.matrix);
  52445. mat.decompose(scaling, rotation, position);
  52446. configureNode(newNode, position, rotation, scaling);
  52447. }
  52448. else {
  52449. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  52450. }
  52451. newNode.computeWorldMatrix(true);
  52452. };
  52453. /**
  52454. * Imports a node
  52455. */
  52456. var importNode = function (gltfRuntime, node, id, parent) {
  52457. var lastNode = null;
  52458. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  52459. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  52460. return null;
  52461. }
  52462. }
  52463. // Meshes
  52464. if (node.skin) {
  52465. if (node.meshes) {
  52466. var skin = gltfRuntime.skins[node.skin];
  52467. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  52468. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  52469. if (newMesh.skeleton === null) {
  52470. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  52471. if (!skin.babylonSkeleton) {
  52472. skin.babylonSkeleton = newMesh.skeleton;
  52473. }
  52474. }
  52475. lastNode = newMesh;
  52476. }
  52477. }
  52478. else if (node.meshes) {
  52479. /**
  52480. * Improve meshes property
  52481. */
  52482. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  52483. lastNode = newMesh;
  52484. }
  52485. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  52486. var light = gltfRuntime.lights[node.light];
  52487. if (light) {
  52488. if (light.type === "ambient") {
  52489. var ambienLight = light[light.type];
  52490. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52491. hemiLight.name = node.name;
  52492. if (ambienLight.color) {
  52493. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  52494. }
  52495. lastNode = hemiLight;
  52496. }
  52497. else if (light.type === "directional") {
  52498. var directionalLight = light[light.type];
  52499. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52500. dirLight.name = node.name;
  52501. if (directionalLight.color) {
  52502. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  52503. }
  52504. lastNode = dirLight;
  52505. }
  52506. else if (light.type === "point") {
  52507. var pointLight = light[light.type];
  52508. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52509. ptLight.name = node.name;
  52510. if (pointLight.color) {
  52511. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  52512. }
  52513. lastNode = ptLight;
  52514. }
  52515. else if (light.type === "spot") {
  52516. var spotLight = light[light.type];
  52517. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  52518. spLight.name = node.name;
  52519. if (spotLight.color) {
  52520. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  52521. }
  52522. if (spotLight.fallOfAngle) {
  52523. spLight.angle = spotLight.fallOfAngle;
  52524. }
  52525. if (spotLight.fallOffExponent) {
  52526. spLight.exponent = spotLight.fallOffExponent;
  52527. }
  52528. lastNode = spLight;
  52529. }
  52530. }
  52531. }
  52532. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  52533. var camera = gltfRuntime.cameras[node.camera];
  52534. if (camera) {
  52535. if (camera.type === "orthographic") {
  52536. var orthographicCamera = camera[camera.type];
  52537. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52538. orthoCamera.name = node.name;
  52539. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  52540. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  52541. lastNode = orthoCamera;
  52542. }
  52543. else if (camera.type === "perspective") {
  52544. var perspectiveCamera = camera[camera.type];
  52545. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  52546. persCamera.name = node.name;
  52547. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  52548. if (!perspectiveCamera.aspectRatio) {
  52549. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  52550. }
  52551. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  52552. persCamera.maxZ = perspectiveCamera.zfar;
  52553. persCamera.minZ = perspectiveCamera.znear;
  52554. }
  52555. lastNode = persCamera;
  52556. }
  52557. }
  52558. }
  52559. // Empty node
  52560. if (!node.jointName) {
  52561. if (node.babylonNode) {
  52562. return node.babylonNode;
  52563. }
  52564. else if (lastNode === null) {
  52565. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  52566. node.babylonNode = dummy;
  52567. lastNode = dummy;
  52568. }
  52569. }
  52570. if (lastNode !== null) {
  52571. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  52572. configureNodeFromMatrix(lastNode, node, parent);
  52573. }
  52574. else {
  52575. var translation = node.translation || [0, 0, 0];
  52576. var rotation = node.rotation || [0, 0, 0, 1];
  52577. var scale = node.scale || [1, 1, 1];
  52578. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  52579. }
  52580. lastNode.updateCache(true);
  52581. node.babylonNode = lastNode;
  52582. }
  52583. return lastNode;
  52584. };
  52585. /**
  52586. * Traverses nodes and creates them
  52587. */
  52588. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  52589. var node = gltfRuntime.nodes[id];
  52590. var newNode = null;
  52591. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  52592. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  52593. meshIncluded = true;
  52594. }
  52595. else {
  52596. meshIncluded = false;
  52597. }
  52598. }
  52599. else {
  52600. meshIncluded = true;
  52601. }
  52602. if (!node.jointName && meshIncluded) {
  52603. newNode = importNode(gltfRuntime, node, id, parent);
  52604. if (newNode !== null) {
  52605. newNode.id = id;
  52606. newNode.parent = parent;
  52607. }
  52608. }
  52609. if (node.children) {
  52610. for (var i = 0; i < node.children.length; i++) {
  52611. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  52612. }
  52613. }
  52614. };
  52615. /**
  52616. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  52617. */
  52618. var postLoad = function (gltfRuntime) {
  52619. // Nodes
  52620. var currentScene = gltfRuntime.currentScene;
  52621. if (currentScene) {
  52622. for (var i = 0; i < currentScene.nodes.length; i++) {
  52623. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52624. }
  52625. }
  52626. else {
  52627. for (var thing in gltfRuntime.scenes) {
  52628. currentScene = gltfRuntime.scenes[thing];
  52629. for (var i = 0; i < currentScene.nodes.length; i++) {
  52630. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  52631. }
  52632. }
  52633. }
  52634. // Set animations
  52635. loadAnimations(gltfRuntime);
  52636. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  52637. var skeleton = gltfRuntime.scene.skeletons[i];
  52638. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  52639. }
  52640. };
  52641. /**
  52642. * onBind shaderrs callback to set uniforms and matrices
  52643. */
  52644. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  52645. var materialValues = material.values || technique.parameters;
  52646. for (var unif in unTreatedUniforms) {
  52647. var uniform = unTreatedUniforms[unif];
  52648. var type = uniform.type;
  52649. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  52650. if (uniform.semantic && !uniform.source && !uniform.node) {
  52651. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  52652. }
  52653. else if (uniform.semantic && (uniform.source || uniform.node)) {
  52654. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  52655. if (source === null) {
  52656. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  52657. }
  52658. if (source === null) {
  52659. continue;
  52660. }
  52661. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  52662. }
  52663. }
  52664. else {
  52665. var value = materialValues[technique.uniforms[unif]];
  52666. if (!value) {
  52667. continue;
  52668. }
  52669. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  52670. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  52671. if (texture === null || texture === undefined) {
  52672. continue;
  52673. }
  52674. shaderMaterial.getEffect().setTexture(unif, texture);
  52675. }
  52676. else {
  52677. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  52678. }
  52679. }
  52680. }
  52681. onSuccess(shaderMaterial);
  52682. };
  52683. /**
  52684. * Prepare uniforms to send the only one time
  52685. * Loads the appropriate textures
  52686. */
  52687. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  52688. var materialValues = material.values || technique.parameters;
  52689. var techniqueUniforms = technique.uniforms;
  52690. /**
  52691. * Prepare values here (not matrices)
  52692. */
  52693. for (var unif in unTreatedUniforms) {
  52694. var uniform = unTreatedUniforms[unif];
  52695. var type = uniform.type;
  52696. var value = materialValues[techniqueUniforms[unif]];
  52697. if (value === undefined) {
  52698. // In case the value is the same for all materials
  52699. value = uniform.value;
  52700. }
  52701. if (!value) {
  52702. continue;
  52703. }
  52704. var onLoadTexture = function (uniformName) {
  52705. return function (texture) {
  52706. if (uniform.value) {
  52707. // Static uniform
  52708. shaderMaterial.setTexture(uniformName, texture);
  52709. delete unTreatedUniforms[uniformName];
  52710. }
  52711. };
  52712. };
  52713. // Texture (sampler2D)
  52714. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  52715. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  52716. }
  52717. else {
  52718. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  52719. // Static uniform
  52720. delete unTreatedUniforms[unif];
  52721. }
  52722. }
  52723. }
  52724. };
  52725. /**
  52726. * Shader compilation failed
  52727. */
  52728. var onShaderCompileError = function (program, shaderMaterial, onError) {
  52729. return function (effect, error) {
  52730. shaderMaterial.dispose(true);
  52731. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  52732. };
  52733. };
  52734. /**
  52735. * Shader compilation success
  52736. */
  52737. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  52738. return function (_) {
  52739. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  52740. shaderMaterial.onBind = function (mesh) {
  52741. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  52742. };
  52743. };
  52744. };
  52745. /**
  52746. * Returns the appropriate uniform if already handled by babylon
  52747. */
  52748. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  52749. for (var unif in technique.uniforms) {
  52750. var uniform = technique.uniforms[unif];
  52751. var uniformParameter = technique.parameters[uniform];
  52752. if (tokenizer.currentIdentifier === unif) {
  52753. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  52754. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  52755. if (transformIndex !== -1) {
  52756. delete unTreatedUniforms[unif];
  52757. return babylonTransforms[transformIndex];
  52758. }
  52759. }
  52760. }
  52761. }
  52762. return tokenizer.currentIdentifier;
  52763. };
  52764. /**
  52765. * All shaders loaded. Create materials one by one
  52766. */
  52767. var importMaterials = function (gltfRuntime) {
  52768. // Create materials
  52769. for (var mat in gltfRuntime.materials) {
  52770. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  52771. }
  52772. };
  52773. /**
  52774. * Implementation of the base glTF spec
  52775. */
  52776. var GLTFLoaderBase = (function () {
  52777. function GLTFLoaderBase() {
  52778. }
  52779. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  52780. var gltfRuntime = {
  52781. extensions: {},
  52782. accessors: {},
  52783. buffers: {},
  52784. bufferViews: {},
  52785. meshes: {},
  52786. lights: {},
  52787. cameras: {},
  52788. nodes: {},
  52789. images: {},
  52790. textures: {},
  52791. shaders: {},
  52792. programs: {},
  52793. samplers: {},
  52794. techniques: {},
  52795. materials: {},
  52796. animations: {},
  52797. skins: {},
  52798. extensionsUsed: [],
  52799. scenes: {},
  52800. buffersCount: 0,
  52801. shaderscount: 0,
  52802. scene: scene,
  52803. rootUrl: rootUrl,
  52804. loadedBufferCount: 0,
  52805. loadedBufferViews: {},
  52806. loadedShaderCount: 0,
  52807. importOnlyMeshes: false,
  52808. dummyNodes: []
  52809. };
  52810. // Parse
  52811. if (parsedData.extensions) {
  52812. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  52813. }
  52814. if (parsedData.extensionsUsed) {
  52815. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  52816. }
  52817. if (parsedData.buffers) {
  52818. parseBuffers(parsedData.buffers, gltfRuntime);
  52819. }
  52820. if (parsedData.bufferViews) {
  52821. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  52822. }
  52823. if (parsedData.accessors) {
  52824. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  52825. }
  52826. if (parsedData.meshes) {
  52827. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  52828. }
  52829. if (parsedData.lights) {
  52830. parseObject(parsedData.lights, "lights", gltfRuntime);
  52831. }
  52832. if (parsedData.cameras) {
  52833. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  52834. }
  52835. if (parsedData.nodes) {
  52836. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  52837. }
  52838. if (parsedData.images) {
  52839. parseObject(parsedData.images, "images", gltfRuntime);
  52840. }
  52841. if (parsedData.textures) {
  52842. parseObject(parsedData.textures, "textures", gltfRuntime);
  52843. }
  52844. if (parsedData.shaders) {
  52845. parseShaders(parsedData.shaders, gltfRuntime);
  52846. }
  52847. if (parsedData.programs) {
  52848. parseObject(parsedData.programs, "programs", gltfRuntime);
  52849. }
  52850. if (parsedData.samplers) {
  52851. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  52852. }
  52853. if (parsedData.techniques) {
  52854. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  52855. }
  52856. if (parsedData.materials) {
  52857. parseObject(parsedData.materials, "materials", gltfRuntime);
  52858. }
  52859. if (parsedData.animations) {
  52860. parseObject(parsedData.animations, "animations", gltfRuntime);
  52861. }
  52862. if (parsedData.skins) {
  52863. parseObject(parsedData.skins, "skins", gltfRuntime);
  52864. }
  52865. if (parsedData.scenes) {
  52866. gltfRuntime.scenes = parsedData.scenes;
  52867. }
  52868. if (parsedData.scene && parsedData.scenes) {
  52869. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  52870. }
  52871. return gltfRuntime;
  52872. };
  52873. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  52874. var buffer = gltfRuntime.buffers[id];
  52875. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  52876. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  52877. }
  52878. else {
  52879. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  52880. onError(request.status + " " + request.statusText);
  52881. });
  52882. }
  52883. };
  52884. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  52885. var texture = gltfRuntime.textures[id];
  52886. if (!texture || !texture.source) {
  52887. onError(null);
  52888. return;
  52889. }
  52890. if (texture.babylonTexture) {
  52891. onSuccess(null);
  52892. return;
  52893. }
  52894. var source = gltfRuntime.images[texture.source];
  52895. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  52896. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  52897. }
  52898. else {
  52899. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  52900. onError(request.status + " " + request.statusText);
  52901. });
  52902. }
  52903. };
  52904. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  52905. var texture = gltfRuntime.textures[id];
  52906. if (texture.babylonTexture) {
  52907. onSuccess(texture.babylonTexture);
  52908. return;
  52909. }
  52910. var sampler = gltfRuntime.samplers[texture.sampler];
  52911. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  52912. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  52913. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  52914. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  52915. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  52916. var blob = new Blob([buffer]);
  52917. var blobURL = URL.createObjectURL(blob);
  52918. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  52919. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  52920. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  52921. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  52922. newTexture.name = id;
  52923. texture.babylonTexture = newTexture;
  52924. onSuccess(newTexture);
  52925. };
  52926. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  52927. var shader = gltfRuntime.shaders[id];
  52928. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  52929. var shaderString = atob(shader.uri.split(",")[1]);
  52930. onSuccess(shaderString);
  52931. }
  52932. else {
  52933. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  52934. onError(request.status + " " + request.statusText);
  52935. });
  52936. }
  52937. };
  52938. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  52939. var material = gltfRuntime.materials[id];
  52940. var technique = gltfRuntime.techniques[material.technique];
  52941. if (!technique) {
  52942. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  52943. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  52944. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  52945. onSuccess(defaultMaterial);
  52946. return;
  52947. }
  52948. var program = gltfRuntime.programs[technique.program];
  52949. var states = technique.states;
  52950. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  52951. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  52952. var newVertexShader = "";
  52953. var newPixelShader = "";
  52954. var vertexTokenizer = new Tokenizer(vertexShader);
  52955. var pixelTokenizer = new Tokenizer(pixelShader);
  52956. var unTreatedUniforms = {};
  52957. var uniforms = [];
  52958. var attributes = [];
  52959. var samplers = [];
  52960. // Fill uniform, sampler2D and attributes
  52961. for (var unif in technique.uniforms) {
  52962. var uniform = technique.uniforms[unif];
  52963. var uniformParameter = technique.parameters[uniform];
  52964. unTreatedUniforms[unif] = uniformParameter;
  52965. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  52966. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  52967. if (transformIndex !== -1) {
  52968. uniforms.push(babylonTransforms[transformIndex]);
  52969. delete unTreatedUniforms[unif];
  52970. }
  52971. else {
  52972. uniforms.push(unif);
  52973. }
  52974. }
  52975. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  52976. samplers.push(unif);
  52977. }
  52978. else {
  52979. uniforms.push(unif);
  52980. }
  52981. }
  52982. for (var attr in technique.attributes) {
  52983. var attribute = technique.attributes[attr];
  52984. var attributeParameter = technique.parameters[attribute];
  52985. if (attributeParameter.semantic) {
  52986. attributes.push(getAttribute(attributeParameter));
  52987. }
  52988. }
  52989. // Configure vertex shader
  52990. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  52991. var tokenType = vertexTokenizer.currentToken;
  52992. if (tokenType !== ETokenType.IDENTIFIER) {
  52993. newVertexShader += vertexTokenizer.currentString;
  52994. continue;
  52995. }
  52996. var foundAttribute = false;
  52997. for (var attr in technique.attributes) {
  52998. var attribute = technique.attributes[attr];
  52999. var attributeParameter = technique.parameters[attribute];
  53000. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  53001. newVertexShader += getAttribute(attributeParameter);
  53002. foundAttribute = true;
  53003. break;
  53004. }
  53005. }
  53006. if (foundAttribute) {
  53007. continue;
  53008. }
  53009. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  53010. }
  53011. // Configure pixel shader
  53012. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  53013. var tokenType = pixelTokenizer.currentToken;
  53014. if (tokenType !== ETokenType.IDENTIFIER) {
  53015. newPixelShader += pixelTokenizer.currentString;
  53016. continue;
  53017. }
  53018. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  53019. }
  53020. // Create shader material
  53021. var shaderPath = {
  53022. vertex: program.vertexShader + id,
  53023. fragment: program.fragmentShader + id
  53024. };
  53025. var options = {
  53026. attributes: attributes,
  53027. uniforms: uniforms,
  53028. samplers: samplers,
  53029. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  53030. };
  53031. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  53032. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  53033. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  53034. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  53035. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  53036. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  53037. if (states && states.functions) {
  53038. var functions = states.functions;
  53039. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  53040. shaderMaterial.backFaceCulling = false;
  53041. }
  53042. var blendFunc = functions.blendFuncSeparate;
  53043. if (blendFunc) {
  53044. 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) {
  53045. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  53046. }
  53047. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  53048. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  53049. }
  53050. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  53051. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  53052. }
  53053. 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) {
  53054. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  53055. }
  53056. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  53057. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  53058. }
  53059. 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) {
  53060. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  53061. }
  53062. }
  53063. }
  53064. };
  53065. return GLTFLoaderBase;
  53066. }());
  53067. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  53068. /**
  53069. * glTF V1 Loader
  53070. */
  53071. var GLTFLoader = (function () {
  53072. function GLTFLoader() {
  53073. }
  53074. GLTFLoader.RegisterExtension = function (extension) {
  53075. if (GLTFLoader.Extensions[extension.name]) {
  53076. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  53077. return;
  53078. }
  53079. GLTFLoader.Extensions[extension.name] = extension;
  53080. };
  53081. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53082. var _this = this;
  53083. scene.useRightHandedSystem = true;
  53084. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  53085. gltfRuntime.importOnlyMeshes = true;
  53086. if (meshesNames === "") {
  53087. gltfRuntime.importMeshesNames = [];
  53088. }
  53089. else if (typeof meshesNames === "string") {
  53090. gltfRuntime.importMeshesNames = [meshesNames];
  53091. }
  53092. else if (meshesNames && !(meshesNames instanceof Array)) {
  53093. gltfRuntime.importMeshesNames = [meshesNames];
  53094. }
  53095. else {
  53096. gltfRuntime.importMeshesNames = [];
  53097. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  53098. }
  53099. // Create nodes
  53100. _this._createNodes(gltfRuntime);
  53101. var meshes = [];
  53102. var skeletons = [];
  53103. // Fill arrays of meshes and skeletons
  53104. for (var nde in gltfRuntime.nodes) {
  53105. var node = gltfRuntime.nodes[nde];
  53106. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  53107. meshes.push(node.babylonNode);
  53108. }
  53109. }
  53110. for (var skl in gltfRuntime.skins) {
  53111. var skin = gltfRuntime.skins[skl];
  53112. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  53113. skeletons.push(skin.babylonSkeleton);
  53114. }
  53115. }
  53116. // Load buffers, shaders, materials, etc.
  53117. _this._loadBuffersAsync(gltfRuntime, function () {
  53118. _this._loadShadersAsync(gltfRuntime, function () {
  53119. importMaterials(gltfRuntime);
  53120. postLoad(gltfRuntime);
  53121. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  53122. onSuccess(meshes, null, skeletons);
  53123. }
  53124. });
  53125. }, onProgress);
  53126. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  53127. onSuccess(meshes, null, skeletons);
  53128. }
  53129. }, onError);
  53130. return true;
  53131. };
  53132. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  53133. var _this = this;
  53134. scene.useRightHandedSystem = true;
  53135. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  53136. // Load runtime extensios
  53137. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  53138. // Create nodes
  53139. _this._createNodes(gltfRuntime);
  53140. // Load buffers, shaders, materials, etc.
  53141. _this._loadBuffersAsync(gltfRuntime, function () {
  53142. _this._loadShadersAsync(gltfRuntime, function () {
  53143. importMaterials(gltfRuntime);
  53144. postLoad(gltfRuntime);
  53145. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  53146. onSuccess();
  53147. }
  53148. });
  53149. });
  53150. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  53151. onSuccess();
  53152. }
  53153. }, onError);
  53154. }, onError);
  53155. };
  53156. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  53157. var hasShaders = false;
  53158. var processShader = function (sha, shader) {
  53159. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  53160. gltfRuntime.loadedShaderCount++;
  53161. if (shaderString) {
  53162. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  53163. }
  53164. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  53165. onload();
  53166. }
  53167. }, function () {
  53168. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  53169. });
  53170. };
  53171. for (var sha in gltfRuntime.shaders) {
  53172. hasShaders = true;
  53173. var shader = gltfRuntime.shaders[sha];
  53174. if (shader) {
  53175. processShader.bind(this, sha, shader)();
  53176. }
  53177. else {
  53178. BABYLON.Tools.Error("No shader named: " + sha);
  53179. }
  53180. }
  53181. if (!hasShaders) {
  53182. onload();
  53183. }
  53184. };
  53185. ;
  53186. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  53187. var hasBuffers = false;
  53188. var processBuffer = function (buf, buffer) {
  53189. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  53190. gltfRuntime.loadedBufferCount++;
  53191. if (bufferView) {
  53192. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  53193. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  53194. }
  53195. gltfRuntime.loadedBufferViews[buf] = bufferView;
  53196. }
  53197. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  53198. onLoad();
  53199. }
  53200. }, function () {
  53201. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  53202. });
  53203. };
  53204. for (var buf in gltfRuntime.buffers) {
  53205. hasBuffers = true;
  53206. var buffer = gltfRuntime.buffers[buf];
  53207. if (buffer) {
  53208. processBuffer.bind(this, buf, buffer)();
  53209. }
  53210. else {
  53211. BABYLON.Tools.Error("No buffer named: " + buf);
  53212. }
  53213. }
  53214. if (!hasBuffers) {
  53215. onLoad();
  53216. }
  53217. };
  53218. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  53219. var currentScene = gltfRuntime.currentScene;
  53220. if (currentScene) {
  53221. // Only one scene even if multiple scenes are defined
  53222. for (var i = 0; i < currentScene.nodes.length; i++) {
  53223. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  53224. }
  53225. }
  53226. else {
  53227. // Load all scenes
  53228. for (var thing in gltfRuntime.scenes) {
  53229. currentScene = gltfRuntime.scenes[thing];
  53230. for (var i = 0; i < currentScene.nodes.length; i++) {
  53231. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  53232. }
  53233. }
  53234. }
  53235. };
  53236. GLTFLoader.Extensions = {};
  53237. return GLTFLoader;
  53238. }());
  53239. GLTF1.GLTFLoader = GLTFLoader;
  53240. ;
  53241. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  53242. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53243. })(BABYLON || (BABYLON = {}));
  53244. //# sourceMappingURL=babylon.glTFLoader.js.map
  53245. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53246. var BABYLON;
  53247. (function (BABYLON) {
  53248. var GLTF1;
  53249. (function (GLTF1) {
  53250. /**
  53251. * Utils functions for GLTF
  53252. */
  53253. var GLTFUtils = (function () {
  53254. function GLTFUtils() {
  53255. }
  53256. /**
  53257. * Sets the given "parameter" matrix
  53258. * @param scene: the {BABYLON.Scene} object
  53259. * @param source: the source node where to pick the matrix
  53260. * @param parameter: the GLTF technique parameter
  53261. * @param uniformName: the name of the shader's uniform
  53262. * @param shaderMaterial: the shader material
  53263. */
  53264. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  53265. var mat = null;
  53266. if (parameter.semantic === "MODEL") {
  53267. mat = source.getWorldMatrix();
  53268. }
  53269. else if (parameter.semantic === "PROJECTION") {
  53270. mat = scene.getProjectionMatrix();
  53271. }
  53272. else if (parameter.semantic === "VIEW") {
  53273. mat = scene.getViewMatrix();
  53274. }
  53275. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  53276. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  53277. }
  53278. else if (parameter.semantic === "MODELVIEW") {
  53279. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  53280. }
  53281. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  53282. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  53283. }
  53284. else if (parameter.semantic === "MODELINVERSE") {
  53285. mat = source.getWorldMatrix().invert();
  53286. }
  53287. else if (parameter.semantic === "VIEWINVERSE") {
  53288. mat = scene.getViewMatrix().invert();
  53289. }
  53290. else if (parameter.semantic === "PROJECTIONINVERSE") {
  53291. mat = scene.getProjectionMatrix().invert();
  53292. }
  53293. else if (parameter.semantic === "MODELVIEWINVERSE") {
  53294. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  53295. }
  53296. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  53297. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  53298. }
  53299. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  53300. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  53301. }
  53302. else {
  53303. debugger;
  53304. }
  53305. switch (parameter.type) {
  53306. case GLTF1.EParameterType.FLOAT_MAT2:
  53307. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  53308. break;
  53309. case GLTF1.EParameterType.FLOAT_MAT3:
  53310. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  53311. break;
  53312. case GLTF1.EParameterType.FLOAT_MAT4:
  53313. shaderMaterial.setMatrix(uniformName, mat);
  53314. break;
  53315. default: break;
  53316. }
  53317. };
  53318. /**
  53319. * Sets the given "parameter" matrix
  53320. * @param shaderMaterial: the shader material
  53321. * @param uniform: the name of the shader's uniform
  53322. * @param value: the value of the uniform
  53323. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  53324. */
  53325. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  53326. switch (type) {
  53327. case GLTF1.EParameterType.FLOAT:
  53328. shaderMaterial.setFloat(uniform, value);
  53329. return true;
  53330. case GLTF1.EParameterType.FLOAT_VEC2:
  53331. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  53332. return true;
  53333. case GLTF1.EParameterType.FLOAT_VEC3:
  53334. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  53335. return true;
  53336. case GLTF1.EParameterType.FLOAT_VEC4:
  53337. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  53338. return true;
  53339. default: return false;
  53340. }
  53341. };
  53342. /**
  53343. * If the uri is a base64 string
  53344. * @param uri: the uri to test
  53345. */
  53346. GLTFUtils.IsBase64 = function (uri) {
  53347. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  53348. };
  53349. /**
  53350. * Decode the base64 uri
  53351. * @param uri: the uri to decode
  53352. */
  53353. GLTFUtils.DecodeBase64 = function (uri) {
  53354. var decodedString = atob(uri.split(",")[1]);
  53355. var bufferLength = decodedString.length;
  53356. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  53357. for (var i = 0; i < bufferLength; i++) {
  53358. bufferView[i] = decodedString.charCodeAt(i);
  53359. }
  53360. return bufferView.buffer;
  53361. };
  53362. /**
  53363. * Returns the wrap mode of the texture
  53364. * @param mode: the mode value
  53365. */
  53366. GLTFUtils.GetWrapMode = function (mode) {
  53367. switch (mode) {
  53368. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  53369. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  53370. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  53371. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  53372. }
  53373. };
  53374. /**
  53375. * Returns the byte stride giving an accessor
  53376. * @param accessor: the GLTF accessor objet
  53377. */
  53378. GLTFUtils.GetByteStrideFromType = function (accessor) {
  53379. // Needs this function since "byteStride" isn't requiered in glTF format
  53380. var type = accessor.type;
  53381. switch (type) {
  53382. case "VEC2": return 2;
  53383. case "VEC3": return 3;
  53384. case "VEC4": return 4;
  53385. case "MAT2": return 4;
  53386. case "MAT3": return 9;
  53387. case "MAT4": return 16;
  53388. default: return 1;
  53389. }
  53390. };
  53391. /**
  53392. * Returns the texture filter mode giving a mode value
  53393. * @param mode: the filter mode value
  53394. */
  53395. GLTFUtils.GetTextureFilterMode = function (mode) {
  53396. switch (mode) {
  53397. case GLTF1.ETextureFilterType.LINEAR:
  53398. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  53399. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  53400. case GLTF1.ETextureFilterType.NEAREST:
  53401. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  53402. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  53403. }
  53404. };
  53405. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  53406. var byteOffset = bufferView.byteOffset + byteOffset;
  53407. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  53408. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  53409. throw new Error("Buffer access is out of range");
  53410. }
  53411. var buffer = loadedBufferView.buffer;
  53412. byteOffset += loadedBufferView.byteOffset;
  53413. switch (componentType) {
  53414. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  53415. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  53416. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  53417. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  53418. default: return new Float32Array(buffer, byteOffset, byteLength);
  53419. }
  53420. };
  53421. /**
  53422. * Returns a buffer from its accessor
  53423. * @param gltfRuntime: the GLTF runtime
  53424. * @param accessor: the GLTF accessor
  53425. */
  53426. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  53427. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  53428. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  53429. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  53430. };
  53431. /**
  53432. * Decodes a buffer view into a string
  53433. * @param view: the buffer view
  53434. */
  53435. GLTFUtils.DecodeBufferToText = function (view) {
  53436. var result = "";
  53437. var length = view.byteLength;
  53438. for (var i = 0; i < length; ++i) {
  53439. result += String.fromCharCode(view[i]);
  53440. }
  53441. return result;
  53442. };
  53443. /**
  53444. * Returns the default material of gltf. Related to
  53445. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  53446. * @param scene: the Babylon.js scene
  53447. */
  53448. GLTFUtils.GetDefaultMaterial = function (scene) {
  53449. if (!GLTFUtils._DefaultMaterial) {
  53450. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  53451. "precision highp float;",
  53452. "",
  53453. "uniform mat4 worldView;",
  53454. "uniform mat4 projection;",
  53455. "",
  53456. "attribute vec3 position;",
  53457. "",
  53458. "void main(void)",
  53459. "{",
  53460. " gl_Position = projection * worldView * vec4(position, 1.0);",
  53461. "}"
  53462. ].join("\n");
  53463. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  53464. "precision highp float;",
  53465. "",
  53466. "uniform vec4 u_emission;",
  53467. "",
  53468. "void main(void)",
  53469. "{",
  53470. " gl_FragColor = u_emission;",
  53471. "}"
  53472. ].join("\n");
  53473. var shaderPath = {
  53474. vertex: "GLTFDefaultMaterial",
  53475. fragment: "GLTFDefaultMaterial"
  53476. };
  53477. var options = {
  53478. attributes: ["position"],
  53479. uniforms: ["worldView", "projection", "u_emission"],
  53480. samplers: [],
  53481. needAlphaBlending: false
  53482. };
  53483. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  53484. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  53485. }
  53486. return GLTFUtils._DefaultMaterial;
  53487. };
  53488. // The GLTF default material
  53489. GLTFUtils._DefaultMaterial = null;
  53490. return GLTFUtils;
  53491. }());
  53492. GLTF1.GLTFUtils = GLTFUtils;
  53493. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53494. })(BABYLON || (BABYLON = {}));
  53495. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  53496. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53497. var BABYLON;
  53498. (function (BABYLON) {
  53499. var GLTF1;
  53500. (function (GLTF1) {
  53501. var GLTFLoaderExtension = (function () {
  53502. function GLTFLoaderExtension(name) {
  53503. this._name = name;
  53504. }
  53505. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  53506. get: function () {
  53507. return this._name;
  53508. },
  53509. enumerable: true,
  53510. configurable: true
  53511. });
  53512. /**
  53513. * Defines an override for loading the runtime
  53514. * Return true to stop further extensions from loading the runtime
  53515. */
  53516. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53517. return false;
  53518. };
  53519. /**
  53520. * Defines an onverride for creating gltf runtime
  53521. * Return true to stop further extensions from creating the runtime
  53522. */
  53523. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53524. return false;
  53525. };
  53526. /**
  53527. * Defines an override for loading buffers
  53528. * Return true to stop further extensions from loading this buffer
  53529. */
  53530. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  53531. return false;
  53532. };
  53533. /**
  53534. * Defines an override for loading texture buffers
  53535. * Return true to stop further extensions from loading this texture data
  53536. */
  53537. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53538. return false;
  53539. };
  53540. /**
  53541. * Defines an override for creating textures
  53542. * Return true to stop further extensions from loading this texture
  53543. */
  53544. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  53545. return false;
  53546. };
  53547. /**
  53548. * Defines an override for loading shader strings
  53549. * Return true to stop further extensions from loading this shader data
  53550. */
  53551. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53552. return false;
  53553. };
  53554. /**
  53555. * Defines an override for loading materials
  53556. * Return true to stop further extensions from loading this material
  53557. */
  53558. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53559. return false;
  53560. };
  53561. // ---------
  53562. // Utilities
  53563. // ---------
  53564. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53565. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53566. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  53567. }, function () {
  53568. setTimeout(function () {
  53569. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  53570. });
  53571. });
  53572. };
  53573. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53574. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53575. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  53576. }, function () {
  53577. setTimeout(function () {
  53578. onSuccess();
  53579. });
  53580. });
  53581. };
  53582. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  53583. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53584. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  53585. }, function () {
  53586. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  53587. });
  53588. };
  53589. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  53590. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  53591. };
  53592. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53593. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53594. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  53595. }, function () {
  53596. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  53597. });
  53598. };
  53599. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53600. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53601. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  53602. }, function () {
  53603. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  53604. });
  53605. };
  53606. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53607. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53608. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  53609. }, function () {
  53610. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  53611. });
  53612. };
  53613. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  53614. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  53615. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  53616. }, function () {
  53617. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  53618. });
  53619. };
  53620. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  53621. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  53622. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  53623. if (func(loaderExtension)) {
  53624. return;
  53625. }
  53626. }
  53627. defaultFunc();
  53628. };
  53629. return GLTFLoaderExtension;
  53630. }());
  53631. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  53632. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53633. })(BABYLON || (BABYLON = {}));
  53634. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  53635. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53636. var BABYLON;
  53637. (function (BABYLON) {
  53638. var GLTF1;
  53639. (function (GLTF1) {
  53640. var BinaryExtensionBufferName = "binary_glTF";
  53641. var EContentFormat;
  53642. (function (EContentFormat) {
  53643. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  53644. })(EContentFormat || (EContentFormat = {}));
  53645. ;
  53646. ;
  53647. ;
  53648. var GLTFBinaryExtension = (function (_super) {
  53649. __extends(GLTFBinaryExtension, _super);
  53650. function GLTFBinaryExtension() {
  53651. return _super.call(this, "KHR_binary_glTF") || this;
  53652. }
  53653. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  53654. var extensionsUsed = data.json.extensionsUsed;
  53655. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  53656. return false;
  53657. }
  53658. this._bin = data.bin;
  53659. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  53660. return true;
  53661. };
  53662. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53663. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  53664. return false;
  53665. }
  53666. if (id !== BinaryExtensionBufferName) {
  53667. return false;
  53668. }
  53669. onSuccess(this._bin);
  53670. return true;
  53671. };
  53672. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  53673. var texture = gltfRuntime.textures[id];
  53674. var source = gltfRuntime.images[texture.source];
  53675. if (!source.extensions || !(this.name in source.extensions)) {
  53676. return false;
  53677. }
  53678. var sourceExt = source.extensions[this.name];
  53679. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  53680. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  53681. onSuccess(buffer);
  53682. return true;
  53683. };
  53684. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  53685. var shader = gltfRuntime.shaders[id];
  53686. if (!shader.extensions || !(this.name in shader.extensions)) {
  53687. return false;
  53688. }
  53689. var binaryExtensionShader = shader.extensions[this.name];
  53690. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  53691. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  53692. setTimeout(function () {
  53693. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  53694. onSuccess(shaderString);
  53695. });
  53696. return true;
  53697. };
  53698. return GLTFBinaryExtension;
  53699. }(GLTF1.GLTFLoaderExtension));
  53700. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  53701. var BinaryReader = (function () {
  53702. function BinaryReader(arrayBuffer) {
  53703. this._arrayBuffer = arrayBuffer;
  53704. this._dataView = new DataView(arrayBuffer);
  53705. this._byteOffset = 0;
  53706. }
  53707. BinaryReader.prototype.getUint32 = function () {
  53708. var value = this._dataView.getUint32(this._byteOffset, true);
  53709. this._byteOffset += 4;
  53710. return value;
  53711. };
  53712. BinaryReader.prototype.getUint8Array = function (length) {
  53713. if (!length) {
  53714. length = this._arrayBuffer.byteLength - this._byteOffset;
  53715. }
  53716. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  53717. this._byteOffset += length;
  53718. return value;
  53719. };
  53720. return BinaryReader;
  53721. }());
  53722. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  53723. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53724. })(BABYLON || (BABYLON = {}));
  53725. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  53726. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53727. var BABYLON;
  53728. (function (BABYLON) {
  53729. var GLTF1;
  53730. (function (GLTF1) {
  53731. ;
  53732. ;
  53733. ;
  53734. var GLTFMaterialsCommonExtension = (function (_super) {
  53735. __extends(GLTFMaterialsCommonExtension, _super);
  53736. function GLTFMaterialsCommonExtension() {
  53737. return _super.call(this, "KHR_materials_common") || this;
  53738. }
  53739. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  53740. if (!gltfRuntime.extensions)
  53741. return false;
  53742. var extension = gltfRuntime.extensions[this.name];
  53743. if (!extension)
  53744. return false;
  53745. // Create lights
  53746. var lights = extension.lights;
  53747. if (lights) {
  53748. for (var thing in lights) {
  53749. var light = lights[thing];
  53750. switch (light.type) {
  53751. case "ambient":
  53752. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  53753. var ambient = light.ambient;
  53754. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  53755. break;
  53756. case "point":
  53757. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  53758. var point = light.point;
  53759. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  53760. break;
  53761. case "directional":
  53762. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  53763. var directional = light.directional;
  53764. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  53765. break;
  53766. case "spot":
  53767. var spot = light.spot;
  53768. 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);
  53769. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  53770. break;
  53771. default:
  53772. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  53773. break;
  53774. }
  53775. }
  53776. }
  53777. return false;
  53778. };
  53779. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  53780. var material = gltfRuntime.materials[id];
  53781. if (!material || !material.extensions)
  53782. return false;
  53783. var extension = material.extensions[this.name];
  53784. if (!extension)
  53785. return false;
  53786. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  53787. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  53788. if (extension.technique === "CONSTANT") {
  53789. standardMaterial.disableLighting = true;
  53790. }
  53791. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  53792. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  53793. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  53794. // Ambient
  53795. if (typeof extension.values.ambient === "string") {
  53796. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  53797. }
  53798. else {
  53799. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  53800. }
  53801. // Diffuse
  53802. if (typeof extension.values.diffuse === "string") {
  53803. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  53804. }
  53805. else {
  53806. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  53807. }
  53808. // Emission
  53809. if (typeof extension.values.emission === "string") {
  53810. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  53811. }
  53812. else {
  53813. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  53814. }
  53815. // Specular
  53816. if (typeof extension.values.specular === "string") {
  53817. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  53818. }
  53819. else {
  53820. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  53821. }
  53822. return true;
  53823. };
  53824. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  53825. // Create buffer from texture url
  53826. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  53827. // Create texture from buffer
  53828. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  53829. }, onError);
  53830. };
  53831. return GLTFMaterialsCommonExtension;
  53832. }(GLTF1.GLTFLoaderExtension));
  53833. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  53834. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  53835. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  53836. })(BABYLON || (BABYLON = {}));
  53837. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  53838. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53839. var BABYLON;
  53840. (function (BABYLON) {
  53841. var GLTF2;
  53842. (function (GLTF2) {
  53843. /**
  53844. * Enums
  53845. */
  53846. var EComponentType;
  53847. (function (EComponentType) {
  53848. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  53849. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  53850. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  53851. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  53852. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  53853. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  53854. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  53855. var EMeshPrimitiveMode;
  53856. (function (EMeshPrimitiveMode) {
  53857. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  53858. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  53859. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  53860. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  53861. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  53862. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  53863. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  53864. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  53865. var ETextureMagFilter;
  53866. (function (ETextureMagFilter) {
  53867. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  53868. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  53869. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  53870. var ETextureMinFilter;
  53871. (function (ETextureMinFilter) {
  53872. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  53873. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  53874. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  53875. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  53876. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  53877. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  53878. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  53879. var ETextureWrapMode;
  53880. (function (ETextureWrapMode) {
  53881. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  53882. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  53883. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  53884. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  53885. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  53886. })(BABYLON || (BABYLON = {}));
  53887. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  53888. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  53889. var BABYLON;
  53890. (function (BABYLON) {
  53891. var GLTF2;
  53892. (function (GLTF2) {
  53893. var GLTFLoader = (function () {
  53894. function GLTFLoader(parent) {
  53895. this._renderReady = false;
  53896. this._disposed = false;
  53897. this._objectURLs = new Array();
  53898. this._blockPendingTracking = false;
  53899. // Observable with boolean indicating success or error.
  53900. this._renderReadyObservable = new BABYLON.Observable();
  53901. // Count of pending work that needs to complete before the asset is rendered.
  53902. this._renderPendingCount = 0;
  53903. // Count of pending work that needs to complete before the loader is cleared.
  53904. this._loaderPendingCount = 0;
  53905. this._parent = parent;
  53906. }
  53907. GLTFLoader.RegisterExtension = function (extension) {
  53908. if (GLTFLoader.Extensions[extension.name]) {
  53909. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  53910. return;
  53911. }
  53912. GLTFLoader.Extensions[extension.name] = extension;
  53913. // Keep the order of registration so that extensions registered first are called first.
  53914. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  53915. };
  53916. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  53917. get: function () {
  53918. return this._gltf;
  53919. },
  53920. enumerable: true,
  53921. configurable: true
  53922. });
  53923. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  53924. get: function () {
  53925. return this._babylonScene;
  53926. },
  53927. enumerable: true,
  53928. configurable: true
  53929. });
  53930. GLTFLoader.prototype.executeWhenRenderReady = function (func) {
  53931. if (this._renderReady) {
  53932. func();
  53933. }
  53934. else {
  53935. this._renderReadyObservable.add(func);
  53936. }
  53937. };
  53938. GLTFLoader.prototype.dispose = function () {
  53939. if (this._disposed) {
  53940. return;
  53941. }
  53942. this._disposed = true;
  53943. // Revoke object urls created during load
  53944. this._objectURLs.forEach(function (url) { return URL.revokeObjectURL(url); });
  53945. this._objectURLs.length = 0;
  53946. this._gltf = undefined;
  53947. this._babylonScene = undefined;
  53948. this._rootUrl = undefined;
  53949. this._defaultMaterial = undefined;
  53950. this._successCallback = undefined;
  53951. this._errorCallback = undefined;
  53952. this._renderReady = false;
  53953. this._renderReadyObservable.clear();
  53954. this._renderPendingCount = 0;
  53955. this._loaderPendingCount = 0;
  53956. };
  53957. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53958. var _this = this;
  53959. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  53960. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  53961. }, onProgress, onError);
  53962. };
  53963. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  53964. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  53965. };
  53966. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  53967. this._loadData(data);
  53968. this._babylonScene = scene;
  53969. this._rootUrl = rootUrl;
  53970. this._successCallback = onSuccess;
  53971. this._progressCallback = onProgress;
  53972. this._errorCallback = onError;
  53973. this.addPendingData(this);
  53974. this._loadScene(nodeNames);
  53975. this._loadAnimations();
  53976. this.removePendingData(this);
  53977. };
  53978. GLTFLoader.prototype._onError = function (message) {
  53979. this._errorCallback(message);
  53980. this.dispose();
  53981. };
  53982. GLTFLoader.prototype._onProgress = function (event) {
  53983. this._progressCallback(event);
  53984. };
  53985. GLTFLoader.prototype._onRenderReady = function () {
  53986. switch (this._parent.coordinateSystemMode) {
  53987. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  53988. if (!this._babylonScene.useRightHandedSystem) {
  53989. this._addRightHandToLeftHandRootTransform();
  53990. }
  53991. break;
  53992. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  53993. // do nothing
  53994. break;
  53995. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  53996. this._babylonScene.useRightHandedSystem = true;
  53997. break;
  53998. default:
  53999. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  54000. break;
  54001. }
  54002. this._showMeshes();
  54003. this._startAnimations();
  54004. this._successCallback();
  54005. this._renderReadyObservable.notifyObservers(this);
  54006. };
  54007. GLTFLoader.prototype._onLoaderComplete = function () {
  54008. if (this._parent.onComplete) {
  54009. this._parent.onComplete();
  54010. }
  54011. };
  54012. GLTFLoader.prototype._onLoaderFirstLODComplete = function () {
  54013. if (this._parent.onFirstLODComplete) {
  54014. this._parent.onFirstLODComplete();
  54015. }
  54016. };
  54017. GLTFLoader.prototype._loadData = function (data) {
  54018. this._gltf = data.json;
  54019. var binaryBuffer;
  54020. var buffers = this._gltf.buffers;
  54021. if (buffers.length > 0 && buffers[0].uri === undefined) {
  54022. binaryBuffer = buffers[0];
  54023. }
  54024. if (data.bin) {
  54025. if (binaryBuffer) {
  54026. if (binaryBuffer.byteLength != data.bin.byteLength) {
  54027. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  54028. }
  54029. }
  54030. else {
  54031. BABYLON.Tools.Warn("Unexpected BIN chunk");
  54032. }
  54033. binaryBuffer.loadedData = data.bin;
  54034. }
  54035. };
  54036. GLTFLoader.prototype._addRightHandToLeftHandRootTransform = function () {
  54037. var rootMesh = new BABYLON.Mesh("root", this._babylonScene);
  54038. rootMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  54039. rootMesh.rotation.y = Math.PI;
  54040. var nodes = this._gltf.nodes;
  54041. for (var i = 0; i < nodes.length; i++) {
  54042. var mesh = nodes[i].babylonMesh;
  54043. if (mesh && !mesh.parent) {
  54044. mesh.parent = rootMesh;
  54045. }
  54046. }
  54047. };
  54048. GLTFLoader.prototype._getMeshes = function () {
  54049. var meshes = [];
  54050. var nodes = this._gltf.nodes;
  54051. if (nodes) {
  54052. nodes.forEach(function (node) {
  54053. if (node.babylonMesh) {
  54054. meshes.push(node.babylonMesh);
  54055. }
  54056. });
  54057. }
  54058. return meshes;
  54059. };
  54060. GLTFLoader.prototype._getSkeletons = function () {
  54061. var skeletons = [];
  54062. var skins = this._gltf.skins;
  54063. if (skins) {
  54064. skins.forEach(function (skin) {
  54065. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  54066. skeletons.push(skin.babylonSkeleton);
  54067. }
  54068. });
  54069. }
  54070. return skeletons;
  54071. };
  54072. GLTFLoader.prototype._getAnimationTargets = function () {
  54073. var targets = [];
  54074. var animations = this._gltf.animations;
  54075. if (animations) {
  54076. animations.forEach(function (animation) {
  54077. targets.push.apply(targets, animation.targets);
  54078. });
  54079. }
  54080. return targets;
  54081. };
  54082. GLTFLoader.prototype._showMeshes = function () {
  54083. this._getMeshes().forEach(function (mesh) { return mesh.isVisible = true; });
  54084. };
  54085. GLTFLoader.prototype._startAnimations = function () {
  54086. var _this = this;
  54087. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  54088. };
  54089. GLTFLoader.prototype._loadScene = function (nodeNames) {
  54090. var _this = this;
  54091. var scene = this._gltf.scenes[this._gltf.scene || 0];
  54092. var nodeIndices = scene.nodes;
  54093. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  54094. node.index = index;
  54095. node.parent = parentNode;
  54096. return true;
  54097. });
  54098. var materials = this._gltf.materials;
  54099. if (materials) {
  54100. materials.forEach(function (material, index) { return material.index = index; });
  54101. }
  54102. if (nodeNames) {
  54103. if (!(nodeNames instanceof Array)) {
  54104. nodeNames = [nodeNames];
  54105. }
  54106. var filteredNodeIndices = new Array();
  54107. this._traverseNodes(nodeIndices, function (node) {
  54108. if (nodeNames.indexOf(node.name) === -1) {
  54109. return true;
  54110. }
  54111. filteredNodeIndices.push(node.index);
  54112. return false;
  54113. });
  54114. nodeIndices = filteredNodeIndices;
  54115. }
  54116. this._traverseNodes(nodeIndices, function (node) { return _this._loadSkin(node); });
  54117. this._traverseNodes(nodeIndices, function (node) { return _this._loadMesh(node); });
  54118. };
  54119. GLTFLoader.prototype._loadSkin = function (node) {
  54120. var _this = this;
  54121. if (node.skin !== undefined) {
  54122. var skin = this._gltf.skins[node.skin];
  54123. var skeletonId = "skeleton" + node.skin;
  54124. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  54125. skin.index = node.skin;
  54126. for (var i = 0; i < skin.joints.length; i++) {
  54127. this._createBone(this._gltf.nodes[skin.joints[i]], skin);
  54128. }
  54129. if (skin.skeleton === undefined) {
  54130. // TODO: handle when skeleton is not defined
  54131. throw new Error("Not implemented");
  54132. }
  54133. if (skin.inverseBindMatrices === undefined) {
  54134. // TODO: handle when inverse bind matrices are not defined
  54135. throw new Error("Not implemented");
  54136. }
  54137. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  54138. this._loadAccessorAsync(accessor, function (data) {
  54139. _this._traverseNode(skin.skeleton, function (node, index, parent) { return _this._updateBone(node, parent, skin, data); });
  54140. });
  54141. }
  54142. return true;
  54143. };
  54144. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  54145. var jointIndex = skin.joints.indexOf(node.index);
  54146. if (jointIndex === -1) {
  54147. this._createBone(node, skin);
  54148. }
  54149. var babylonBone = node.babylonSkinToBones[skin.index];
  54150. // TODO: explain the math
  54151. var matrix = jointIndex === -1 ? BABYLON.Matrix.Identity() : BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  54152. matrix.invertToRef(matrix);
  54153. if (parentNode) {
  54154. babylonBone.setParent(parentNode.babylonSkinToBones[skin.index], false);
  54155. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  54156. }
  54157. babylonBone.updateMatrix(matrix);
  54158. return true;
  54159. };
  54160. GLTFLoader.prototype._createBone = function (node, skin) {
  54161. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton);
  54162. node.babylonSkinToBones = node.babylonSkinToBones || {};
  54163. node.babylonSkinToBones[skin.index] = babylonBone;
  54164. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  54165. node.babylonAnimationTargets.push(babylonBone);
  54166. return babylonBone;
  54167. };
  54168. GLTFLoader.prototype._loadMesh = function (node) {
  54169. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  54170. babylonMesh.isVisible = false;
  54171. this._loadTransform(node, babylonMesh);
  54172. if (node.mesh !== undefined) {
  54173. var mesh = this._gltf.meshes[node.mesh];
  54174. this._loadMeshData(node, mesh, babylonMesh);
  54175. }
  54176. babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  54177. node.babylonMesh = babylonMesh;
  54178. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  54179. node.babylonAnimationTargets.push(node.babylonMesh);
  54180. if (node.skin !== undefined) {
  54181. var skin = this._gltf.skins[node.skin];
  54182. babylonMesh.skeleton = skin.babylonSkeleton;
  54183. }
  54184. if (node.camera !== undefined) {
  54185. // TODO: handle cameras
  54186. }
  54187. return true;
  54188. };
  54189. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  54190. var _this = this;
  54191. babylonMesh.name = mesh.name || babylonMesh.name;
  54192. var babylonMultiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  54193. babylonMesh.material = babylonMultiMaterial;
  54194. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  54195. var vertexData = new BABYLON.VertexData();
  54196. vertexData.positions = [];
  54197. vertexData.indices = [];
  54198. var subMeshInfos = [];
  54199. var loadedPrimitives = 0;
  54200. var totalPrimitives = mesh.primitives.length;
  54201. var _loop_1 = function (i) {
  54202. var primitive = mesh.primitives[i];
  54203. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  54204. // TODO: handle other primitive modes
  54205. throw new Error("Not implemented");
  54206. }
  54207. this_1._createMorphTargets(node, mesh, primitive, babylonMesh);
  54208. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  54209. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  54210. subMeshInfos.push({
  54211. materialIndex: i,
  54212. verticesStart: vertexData.positions.length,
  54213. verticesCount: subVertexData.positions.length,
  54214. indicesStart: vertexData.indices.length,
  54215. indicesCount: subVertexData.indices.length,
  54216. loadMaterial: function () {
  54217. if (primitive.material === undefined) {
  54218. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  54219. }
  54220. else {
  54221. var material = _this._gltf.materials[primitive.material];
  54222. _this.loadMaterial(material, function (babylonMaterial, isNew) {
  54223. if (isNew && _this._parent.onMaterialLoaded) {
  54224. _this._parent.onMaterialLoaded(babylonMaterial);
  54225. }
  54226. if (_this._parent.onBeforeMaterialReadyAsync) {
  54227. _this.addLoaderPendingData(material);
  54228. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, babylonMesh, babylonMultiMaterial.subMaterials[i] != null, function () {
  54229. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  54230. _this.removeLoaderPendingData(material);
  54231. });
  54232. }
  54233. else {
  54234. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  54235. }
  54236. });
  54237. }
  54238. }
  54239. });
  54240. vertexData.merge(subVertexData);
  54241. if (++loadedPrimitives === totalPrimitives) {
  54242. geometry.setAllVerticesData(vertexData, false);
  54243. subMeshInfos.forEach(function (info) { return info.loadMaterial(); });
  54244. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  54245. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  54246. babylonMesh.subMeshes = [];
  54247. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, babylonMesh); });
  54248. }
  54249. });
  54250. };
  54251. var this_1 = this;
  54252. for (var i = 0; i < totalPrimitives; i++) {
  54253. _loop_1(i);
  54254. }
  54255. };
  54256. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  54257. var _this = this;
  54258. var attributes = primitive.attributes;
  54259. if (!attributes) {
  54260. this._onError("Primitive has no attributes");
  54261. return;
  54262. }
  54263. var vertexData = new BABYLON.VertexData();
  54264. var loadedAttributes = 0;
  54265. var totalAttributes = Object.keys(attributes).length;
  54266. var _loop_2 = function (semantic) {
  54267. accessor = this_2._gltf.accessors[attributes[semantic]];
  54268. this_2._loadAccessorAsync(accessor, function (data) {
  54269. switch (semantic) {
  54270. case "NORMAL":
  54271. vertexData.normals = data;
  54272. break;
  54273. case "POSITION":
  54274. vertexData.positions = data;
  54275. break;
  54276. case "TANGENT":
  54277. vertexData.tangents = data;
  54278. break;
  54279. case "TEXCOORD_0":
  54280. vertexData.uvs = data;
  54281. break;
  54282. case "TEXCOORD_1":
  54283. vertexData.uvs2 = data;
  54284. break;
  54285. case "JOINTS_0":
  54286. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  54287. break;
  54288. case "WEIGHTS_0":
  54289. vertexData.matricesWeights = data;
  54290. break;
  54291. case "COLOR_0":
  54292. vertexData.colors = data;
  54293. break;
  54294. default:
  54295. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  54296. break;
  54297. }
  54298. if (++loadedAttributes === totalAttributes) {
  54299. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  54300. if (indicesAccessor) {
  54301. _this._loadAccessorAsync(indicesAccessor, function (data) {
  54302. vertexData.indices = data;
  54303. onSuccess(vertexData);
  54304. });
  54305. }
  54306. else {
  54307. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  54308. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  54309. onSuccess(vertexData);
  54310. }
  54311. }
  54312. });
  54313. };
  54314. var this_2 = this, accessor;
  54315. for (var semantic in attributes) {
  54316. _loop_2(semantic);
  54317. }
  54318. };
  54319. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  54320. var targets = primitive.targets;
  54321. if (!targets) {
  54322. return;
  54323. }
  54324. if (!babylonMesh.morphTargetManager) {
  54325. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  54326. }
  54327. for (var index = 0; index < targets.length; index++) {
  54328. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  54329. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  54330. }
  54331. };
  54332. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  54333. var targets = primitive.targets;
  54334. if (!targets) {
  54335. return;
  54336. }
  54337. var _loop_3 = function () {
  54338. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  54339. attributes = targets[index];
  54340. var _loop_4 = function (semantic) {
  54341. accessor = this_3._gltf.accessors[attributes[semantic]];
  54342. this_3._loadAccessorAsync(accessor, function (data) {
  54343. if (accessor.name) {
  54344. babylonMorphTarget.name = accessor.name;
  54345. }
  54346. // glTF stores morph target information as deltas while babylon.js expects the final data.
  54347. // As a result we have to add the original data to the delta to calculate the final data.
  54348. var values = data;
  54349. switch (semantic) {
  54350. case "NORMAL":
  54351. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  54352. babylonMorphTarget.setNormals(values);
  54353. break;
  54354. case "POSITION":
  54355. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  54356. babylonMorphTarget.setPositions(values);
  54357. break;
  54358. case "TANGENT":
  54359. // Tangent data for morph targets is stored as xyz delta.
  54360. // The vertexData.tangent is stored as xyzw.
  54361. // So we need to skip every fourth vertexData.tangent.
  54362. for (var i = 0, j = 0; i < values.length; i++, j++) {
  54363. values[i] += vertexData.tangents[j];
  54364. if ((i + 1) % 3 == 0) {
  54365. j++;
  54366. }
  54367. }
  54368. babylonMorphTarget.setTangents(values);
  54369. break;
  54370. default:
  54371. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  54372. break;
  54373. }
  54374. });
  54375. };
  54376. for (var semantic in attributes) {
  54377. _loop_4(semantic);
  54378. }
  54379. };
  54380. var this_3 = this, attributes, accessor;
  54381. for (var index = 0; index < targets.length; index++) {
  54382. _loop_3();
  54383. }
  54384. };
  54385. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  54386. var position = BABYLON.Vector3.Zero();
  54387. var rotation = BABYLON.Quaternion.Identity();
  54388. var scaling = BABYLON.Vector3.One();
  54389. if (node.matrix) {
  54390. var mat = BABYLON.Matrix.FromArray(node.matrix);
  54391. mat.decompose(scaling, rotation, position);
  54392. }
  54393. else {
  54394. if (node.translation)
  54395. position = BABYLON.Vector3.FromArray(node.translation);
  54396. if (node.rotation)
  54397. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  54398. if (node.scale)
  54399. scaling = BABYLON.Vector3.FromArray(node.scale);
  54400. }
  54401. babylonMesh.position = position;
  54402. babylonMesh.rotationQuaternion = rotation;
  54403. babylonMesh.scaling = scaling;
  54404. };
  54405. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  54406. if (parentNode === void 0) { parentNode = null; }
  54407. for (var i = 0; i < indices.length; i++) {
  54408. this._traverseNode(indices[i], action, parentNode);
  54409. }
  54410. };
  54411. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  54412. if (parentNode === void 0) { parentNode = null; }
  54413. var node = this._gltf.nodes[index];
  54414. if (!action(node, index, parentNode)) {
  54415. return;
  54416. }
  54417. if (node.children) {
  54418. for (var i = 0; i < node.children.length; i++) {
  54419. this._traverseNode(node.children[i], action, node);
  54420. }
  54421. }
  54422. };
  54423. GLTFLoader.prototype._loadAnimations = function () {
  54424. var animations = this._gltf.animations;
  54425. if (!animations || animations.length === 0) {
  54426. return;
  54427. }
  54428. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  54429. var animation = animations[animationIndex];
  54430. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  54431. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  54432. }
  54433. }
  54434. };
  54435. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  54436. var channel = animation.channels[channelIndex];
  54437. var samplerIndex = channel.sampler;
  54438. var sampler = animation.samplers[samplerIndex];
  54439. var targetNode = this._gltf.nodes[channel.target.node];
  54440. if (!targetNode) {
  54441. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  54442. return;
  54443. }
  54444. var targetPath = {
  54445. "translation": "position",
  54446. "rotation": "rotationQuaternion",
  54447. "scale": "scaling",
  54448. "weights": "influence"
  54449. }[channel.target.path];
  54450. if (!targetPath) {
  54451. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  54452. return;
  54453. }
  54454. var animationType = {
  54455. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  54456. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  54457. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  54458. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  54459. }[targetPath];
  54460. var inputData;
  54461. var outputData;
  54462. var checkSuccess = function () {
  54463. if (!inputData || !outputData) {
  54464. return;
  54465. }
  54466. var outputBufferOffset = 0;
  54467. var getNextOutputValue = {
  54468. "position": function () {
  54469. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  54470. outputBufferOffset += 3;
  54471. return value;
  54472. },
  54473. "rotationQuaternion": function () {
  54474. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  54475. outputBufferOffset += 4;
  54476. return value;
  54477. },
  54478. "scaling": function () {
  54479. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  54480. outputBufferOffset += 3;
  54481. return value;
  54482. },
  54483. "influence": function () {
  54484. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  54485. var value = new Array(numTargets);
  54486. for (var i = 0; i < numTargets; i++) {
  54487. value[i] = outputData[outputBufferOffset++];
  54488. }
  54489. return value;
  54490. },
  54491. }[targetPath];
  54492. var getNextKey = {
  54493. "LINEAR": function (frameIndex) { return ({
  54494. frame: inputData[frameIndex],
  54495. value: getNextOutputValue()
  54496. }); },
  54497. "CUBICSPLINE": function (frameIndex) { return ({
  54498. frame: inputData[frameIndex],
  54499. inTangent: getNextOutputValue(),
  54500. value: getNextOutputValue(),
  54501. outTangent: getNextOutputValue()
  54502. }); },
  54503. }[sampler.interpolation];
  54504. var keys = new Array(inputData.length);
  54505. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  54506. keys[frameIndex] = getNextKey(frameIndex);
  54507. }
  54508. animation.targets = animation.targets || [];
  54509. if (targetPath === "influence") {
  54510. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  54511. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  54512. var morphTarget = morphTargetManager.getTarget(targetIndex);
  54513. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  54514. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  54515. babylonAnimation.setKeys(keys.map(function (key) { return ({
  54516. frame: key.frame,
  54517. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  54518. value: key.value[targetIndex],
  54519. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  54520. }); }));
  54521. morphTarget.animations.push(babylonAnimation);
  54522. animation.targets.push(morphTarget);
  54523. }
  54524. }
  54525. else {
  54526. var animationName = animation.name || "anim" + animationIndex;
  54527. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  54528. babylonAnimation.setKeys(keys);
  54529. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  54530. var target = targetNode.babylonAnimationTargets[i];
  54531. target.animations.push(babylonAnimation.clone());
  54532. animation.targets.push(target);
  54533. }
  54534. }
  54535. };
  54536. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  54537. inputData = data;
  54538. checkSuccess();
  54539. });
  54540. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  54541. outputData = data;
  54542. checkSuccess();
  54543. });
  54544. };
  54545. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  54546. var _this = this;
  54547. var buffer = this._gltf.buffers[index];
  54548. this.addPendingData(buffer);
  54549. if (buffer.loadedData) {
  54550. setTimeout(function () {
  54551. onSuccess(buffer.loadedData);
  54552. _this.removePendingData(buffer);
  54553. });
  54554. }
  54555. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  54556. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  54557. buffer.loadedData = new Uint8Array(data);
  54558. setTimeout(function () {
  54559. onSuccess(buffer.loadedData);
  54560. _this.removePendingData(buffer);
  54561. });
  54562. }
  54563. else if (buffer.loadedObservable) {
  54564. buffer.loadedObservable.add(function (buffer) {
  54565. onSuccess(buffer.loadedData);
  54566. _this.removePendingData(buffer);
  54567. });
  54568. }
  54569. else {
  54570. buffer.loadedObservable = new BABYLON.Observable();
  54571. buffer.loadedObservable.add(function (buffer) {
  54572. onSuccess(buffer.loadedData);
  54573. _this.removePendingData(buffer);
  54574. });
  54575. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  54576. buffer.loadedData = new Uint8Array(data);
  54577. buffer.loadedObservable.notifyObservers(buffer);
  54578. buffer.loadedObservable = null;
  54579. }, function (event) {
  54580. if (!_this._disposed) {
  54581. _this._onProgress(event);
  54582. }
  54583. }, this._babylonScene.database, true, function (request) {
  54584. if (!_this._disposed) {
  54585. _this._onError("Failed to load file '" + buffer.uri + "': " + request.status + " " + request.statusText);
  54586. _this.removePendingData(buffer);
  54587. }
  54588. });
  54589. }
  54590. };
  54591. GLTFLoader.prototype._buildInt8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54592. if (!byteStride) {
  54593. return new Int8Array(buffer, byteOffset, byteLength);
  54594. }
  54595. var sourceBuffer = new Int8Array(buffer, byteOffset);
  54596. var targetBuffer = new Int8Array(byteLength);
  54597. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  54598. return targetBuffer;
  54599. };
  54600. GLTFLoader.prototype._buildUint8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54601. if (!byteStride) {
  54602. return new Uint8Array(buffer, byteOffset, byteLength);
  54603. }
  54604. var sourceBuffer = new Uint8Array(buffer, byteOffset);
  54605. var targetBuffer = new Uint8Array(byteLength);
  54606. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  54607. return targetBuffer;
  54608. };
  54609. GLTFLoader.prototype._buildInt16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54610. if (!byteStride) {
  54611. return new Int16Array(buffer, byteOffset, byteLength);
  54612. }
  54613. var sourceBuffer = new Int16Array(buffer, byteOffset);
  54614. var targetBuffer = new Int16Array(byteLength);
  54615. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  54616. return targetBuffer;
  54617. };
  54618. GLTFLoader.prototype._buildUint16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54619. if (!byteStride) {
  54620. return new Uint16Array(buffer, byteOffset, byteLength);
  54621. }
  54622. var sourceBuffer = new Uint16Array(buffer, byteOffset);
  54623. var targetBuffer = new Uint16Array(byteLength);
  54624. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  54625. return targetBuffer;
  54626. };
  54627. GLTFLoader.prototype._buildUint32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54628. if (!byteStride) {
  54629. return new Uint32Array(buffer, byteOffset, byteLength);
  54630. }
  54631. var sourceBuffer = new Uint32Array(buffer, byteOffset);
  54632. var targetBuffer = new Uint32Array(byteLength);
  54633. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  54634. return targetBuffer;
  54635. };
  54636. GLTFLoader.prototype._buildFloat32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  54637. if (!byteStride) {
  54638. return new Float32Array(buffer, byteOffset, byteLength);
  54639. }
  54640. var sourceBuffer = new Float32Array(buffer, byteOffset);
  54641. var targetBuffer = new Float32Array(byteLength);
  54642. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  54643. return targetBuffer;
  54644. };
  54645. GLTFLoader.prototype._extractInterleavedData = function (sourceBuffer, targetBuffer, bytePerComponent, stride, length) {
  54646. var tempIndex = 0;
  54647. var sourceIndex = 0;
  54648. var storageSize = bytePerComponent;
  54649. while (tempIndex < length) {
  54650. for (var cursor = 0; cursor < storageSize; cursor++) {
  54651. targetBuffer[tempIndex] = sourceBuffer[sourceIndex + cursor];
  54652. tempIndex++;
  54653. }
  54654. sourceIndex += stride;
  54655. }
  54656. };
  54657. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, bytePerComponent, componentType, onSuccess) {
  54658. var _this = this;
  54659. byteOffset += (bufferView.byteOffset || 0);
  54660. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  54661. if (byteOffset + byteLength > bufferData.byteLength) {
  54662. _this._onError("Buffer access is out of range");
  54663. return;
  54664. }
  54665. var buffer = bufferData.buffer;
  54666. byteOffset += bufferData.byteOffset;
  54667. var bufferViewData;
  54668. switch (componentType) {
  54669. case GLTF2.EComponentType.BYTE:
  54670. bufferViewData = _this._buildInt8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54671. break;
  54672. case GLTF2.EComponentType.UNSIGNED_BYTE:
  54673. bufferViewData = _this._buildUint8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54674. break;
  54675. case GLTF2.EComponentType.SHORT:
  54676. bufferViewData = _this._buildInt16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54677. break;
  54678. case GLTF2.EComponentType.UNSIGNED_SHORT:
  54679. bufferViewData = _this._buildUint16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54680. break;
  54681. case GLTF2.EComponentType.UNSIGNED_INT:
  54682. bufferViewData = _this._buildUint32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54683. break;
  54684. case GLTF2.EComponentType.FLOAT:
  54685. bufferViewData = _this._buildFloat32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  54686. break;
  54687. default:
  54688. _this._onError("Invalid component type (" + componentType + ")");
  54689. return;
  54690. }
  54691. onSuccess(bufferViewData);
  54692. });
  54693. };
  54694. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  54695. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  54696. var byteOffset = accessor.byteOffset || 0;
  54697. var bytePerComponent = this._getByteStrideFromType(accessor);
  54698. var byteLength = accessor.count * bytePerComponent;
  54699. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, bytePerComponent, accessor.componentType, onSuccess);
  54700. };
  54701. GLTFLoader.prototype._getByteStrideFromType = function (accessor) {
  54702. switch (accessor.type) {
  54703. case "SCALAR": return 1;
  54704. case "VEC2": return 2;
  54705. case "VEC3": return 3;
  54706. case "VEC4": return 4;
  54707. case "MAT2": return 4;
  54708. case "MAT3": return 9;
  54709. case "MAT4": return 16;
  54710. default:
  54711. this._onError("Invalid accessor type (" + accessor.type + ")");
  54712. return 0;
  54713. }
  54714. };
  54715. Object.defineProperty(GLTFLoader.prototype, "blockPendingTracking", {
  54716. set: function (value) {
  54717. this._blockPendingTracking = value;
  54718. },
  54719. enumerable: true,
  54720. configurable: true
  54721. });
  54722. GLTFLoader.prototype.addPendingData = function (data) {
  54723. if (!this._renderReady) {
  54724. this._renderPendingCount++;
  54725. }
  54726. this.addLoaderPendingData(data);
  54727. };
  54728. GLTFLoader.prototype.removePendingData = function (data) {
  54729. if (!this._renderReady) {
  54730. if (--this._renderPendingCount === 0) {
  54731. this._renderReady = true;
  54732. this._onRenderReady();
  54733. }
  54734. }
  54735. this.removeLoaderPendingData(data);
  54736. };
  54737. GLTFLoader.prototype.addLoaderNonBlockingPendingData = function (data) {
  54738. if (!this._nonBlockingData) {
  54739. this._nonBlockingData = new Array();
  54740. }
  54741. this._nonBlockingData.push(data);
  54742. };
  54743. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  54744. if (this._blockPendingTracking) {
  54745. this.addLoaderNonBlockingPendingData(data);
  54746. return;
  54747. }
  54748. this._loaderPendingCount++;
  54749. };
  54750. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  54751. var indexInPending = this._nonBlockingData ? this._nonBlockingData.indexOf(data) : -1;
  54752. if (indexInPending !== -1) {
  54753. this._nonBlockingData.splice(indexInPending, 1);
  54754. }
  54755. else if (--this._loaderPendingCount === 0) {
  54756. this._onLoaderFirstLODComplete();
  54757. }
  54758. if ((!this._nonBlockingData || this._nonBlockingData.length === 0) && this._loaderPendingCount === 0) {
  54759. this._onLoaderComplete();
  54760. this.dispose();
  54761. }
  54762. };
  54763. GLTFLoader.prototype._getDefaultMaterial = function () {
  54764. if (!this._defaultMaterial) {
  54765. var id = "__gltf_default";
  54766. var material = this._babylonScene.getMaterialByName(id);
  54767. if (!material) {
  54768. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  54769. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  54770. material.metallic = 1;
  54771. material.roughness = 1;
  54772. }
  54773. this._defaultMaterial = material;
  54774. }
  54775. return this._defaultMaterial;
  54776. };
  54777. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  54778. var babylonMaterial = material.babylonMaterial;
  54779. // Ensure metallic workflow
  54780. babylonMaterial.metallic = 1;
  54781. babylonMaterial.roughness = 1;
  54782. var properties = material.pbrMetallicRoughness;
  54783. if (!properties) {
  54784. return;
  54785. }
  54786. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  54787. babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  54788. babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  54789. if (properties.baseColorTexture) {
  54790. babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  54791. }
  54792. if (properties.metallicRoughnessTexture) {
  54793. babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  54794. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  54795. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  54796. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  54797. }
  54798. this.loadMaterialAlphaProperties(material, properties.baseColorFactor);
  54799. };
  54800. GLTFLoader.prototype.loadMaterial = function (material, assign) {
  54801. if (material.babylonMaterial) {
  54802. assign(material.babylonMaterial, false);
  54803. return;
  54804. }
  54805. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  54806. return;
  54807. }
  54808. this.createPbrMaterial(material);
  54809. this.loadMaterialBaseProperties(material);
  54810. this._loadMaterialMetallicRoughnessProperties(material);
  54811. assign(material.babylonMaterial, true);
  54812. };
  54813. GLTFLoader.prototype.createPbrMaterial = function (material) {
  54814. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  54815. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  54816. material.babylonMaterial = babylonMaterial;
  54817. };
  54818. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  54819. var babylonMaterial = material.babylonMaterial;
  54820. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  54821. if (material.doubleSided) {
  54822. babylonMaterial.backFaceCulling = false;
  54823. babylonMaterial.twoSidedLighting = true;
  54824. }
  54825. if (material.normalTexture) {
  54826. babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  54827. babylonMaterial.invertNormalMapX = true;
  54828. babylonMaterial.invertNormalMapY = false;
  54829. if (material.normalTexture.scale !== undefined) {
  54830. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  54831. }
  54832. }
  54833. if (material.occlusionTexture) {
  54834. babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  54835. babylonMaterial.useAmbientInGrayScale = true;
  54836. if (material.occlusionTexture.strength !== undefined) {
  54837. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  54838. }
  54839. }
  54840. if (material.emissiveTexture) {
  54841. babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  54842. }
  54843. };
  54844. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material, colorFactor) {
  54845. var babylonMaterial = material.babylonMaterial;
  54846. var alphaMode = material.alphaMode || "OPAQUE";
  54847. switch (alphaMode) {
  54848. case "OPAQUE":
  54849. // default is opaque
  54850. break;
  54851. case "MASK":
  54852. case "BLEND":
  54853. if (colorFactor) {
  54854. babylonMaterial.alpha = colorFactor[3];
  54855. }
  54856. if (babylonMaterial.albedoTexture) {
  54857. babylonMaterial.albedoTexture.hasAlpha = true;
  54858. babylonMaterial.useAlphaFromAlbedoTexture = (alphaMode === "BLEND");
  54859. }
  54860. break;
  54861. default:
  54862. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  54863. break;
  54864. }
  54865. };
  54866. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  54867. var _this = this;
  54868. var texture = this._gltf.textures[textureInfo.index];
  54869. var texCoord = textureInfo.texCoord || 0;
  54870. if (!texture || texture.source === undefined) {
  54871. return null;
  54872. }
  54873. // check the cache first
  54874. var babylonTexture;
  54875. if (texture.babylonTextures) {
  54876. babylonTexture = texture.babylonTextures[texCoord];
  54877. if (!babylonTexture) {
  54878. for (var i = 0; i < texture.babylonTextures.length; i++) {
  54879. babylonTexture = texture.babylonTextures[i];
  54880. if (babylonTexture) {
  54881. babylonTexture = babylonTexture.clone();
  54882. babylonTexture.coordinatesIndex = texCoord;
  54883. break;
  54884. }
  54885. }
  54886. }
  54887. return babylonTexture;
  54888. }
  54889. var source = this._gltf.images[texture.source];
  54890. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  54891. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  54892. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  54893. this.addPendingData(texture);
  54894. babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  54895. if (!_this._disposed) {
  54896. _this.removePendingData(texture);
  54897. }
  54898. }, function () {
  54899. if (!_this._disposed) {
  54900. _this._onError("Failed to load texture '" + source.uri + "'");
  54901. _this.removePendingData(texture);
  54902. }
  54903. });
  54904. var setTextureData = function (data) {
  54905. var url = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  54906. _this._objectURLs.push(url);
  54907. babylonTexture.updateURL(url);
  54908. };
  54909. if (!source.uri) {
  54910. var bufferView = this._gltf.bufferViews[source.bufferView];
  54911. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, 1, GLTF2.EComponentType.UNSIGNED_BYTE, setTextureData);
  54912. }
  54913. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  54914. setTextureData(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri)));
  54915. }
  54916. else {
  54917. BABYLON.Tools.LoadFile(this._rootUrl + source.uri, setTextureData, function (event) {
  54918. if (!_this._disposed) {
  54919. _this._onProgress(event);
  54920. }
  54921. }, this._babylonScene.database, true, function (request) {
  54922. _this._onError("Failed to load file '" + source.uri + "': " + request.status + " " + request.statusText);
  54923. });
  54924. }
  54925. babylonTexture.coordinatesIndex = texCoord;
  54926. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  54927. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  54928. babylonTexture.name = texture.name || "texture" + textureInfo.index;
  54929. // Cache the texture
  54930. texture.babylonTextures = texture.babylonTextures || [];
  54931. texture.babylonTextures[texCoord] = babylonTexture;
  54932. if (this._parent.onTextureLoaded) {
  54933. this._parent.onTextureLoaded(babylonTexture);
  54934. }
  54935. return babylonTexture;
  54936. };
  54937. GLTFLoader.Extensions = {};
  54938. return GLTFLoader;
  54939. }());
  54940. GLTF2.GLTFLoader = GLTFLoader;
  54941. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  54942. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  54943. })(BABYLON || (BABYLON = {}));
  54944. //# sourceMappingURL=babylon.glTFLoader.js.map
  54945. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  54946. var BABYLON;
  54947. (function (BABYLON) {
  54948. var GLTF2;
  54949. (function (GLTF2) {
  54950. /**
  54951. * Utils functions for GLTF
  54952. */
  54953. var GLTFUtils = (function () {
  54954. function GLTFUtils() {
  54955. }
  54956. /**
  54957. * If the uri is a base64 string
  54958. * @param uri: the uri to test
  54959. */
  54960. GLTFUtils.IsBase64 = function (uri) {
  54961. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  54962. };
  54963. /**
  54964. * Decode the base64 uri
  54965. * @param uri: the uri to decode
  54966. */
  54967. GLTFUtils.DecodeBase64 = function (uri) {
  54968. var decodedString = atob(uri.split(",")[1]);
  54969. var bufferLength = decodedString.length;
  54970. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  54971. for (var i = 0; i < bufferLength; i++) {
  54972. bufferView[i] = decodedString.charCodeAt(i);
  54973. }
  54974. return bufferView.buffer;
  54975. };
  54976. GLTFUtils.ForEach = function (view, func) {
  54977. for (var index = 0; index < view.length; index++) {
  54978. func(view[index], index);
  54979. }
  54980. };
  54981. GLTFUtils.GetTextureWrapMode = function (mode) {
  54982. // Set defaults if undefined
  54983. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  54984. switch (mode) {
  54985. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  54986. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  54987. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  54988. default:
  54989. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  54990. return BABYLON.Texture.WRAP_ADDRESSMODE;
  54991. }
  54992. };
  54993. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  54994. // Set defaults if undefined
  54995. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  54996. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST : minFilter;
  54997. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  54998. switch (minFilter) {
  54999. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  55000. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  55001. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  55002. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  55003. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  55004. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  55005. default:
  55006. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  55007. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  55008. }
  55009. }
  55010. else {
  55011. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  55012. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  55013. }
  55014. switch (minFilter) {
  55015. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  55016. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  55017. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  55018. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  55019. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  55020. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  55021. default:
  55022. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  55023. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  55024. }
  55025. }
  55026. };
  55027. /**
  55028. * Decodes a buffer view into a string
  55029. * @param view: the buffer view
  55030. */
  55031. GLTFUtils.DecodeBufferToText = function (view) {
  55032. var result = "";
  55033. var length = view.byteLength;
  55034. for (var i = 0; i < length; ++i) {
  55035. result += String.fromCharCode(view[i]);
  55036. }
  55037. return result;
  55038. };
  55039. return GLTFUtils;
  55040. }());
  55041. GLTF2.GLTFUtils = GLTFUtils;
  55042. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  55043. })(BABYLON || (BABYLON = {}));
  55044. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  55045. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  55046. var BABYLON;
  55047. (function (BABYLON) {
  55048. var GLTF2;
  55049. (function (GLTF2) {
  55050. var GLTFLoaderExtension = (function () {
  55051. function GLTFLoaderExtension() {
  55052. this.enabled = true;
  55053. }
  55054. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  55055. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  55056. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  55057. };
  55058. GLTFLoaderExtension._ApplyExtensions = function (action) {
  55059. var extensions = GLTFLoaderExtension._Extensions;
  55060. if (!extensions) {
  55061. return;
  55062. }
  55063. for (var i = 0; i < extensions.length; i++) {
  55064. var extension = extensions[i];
  55065. if (extension.enabled && action(extension)) {
  55066. return true;
  55067. }
  55068. }
  55069. return false;
  55070. };
  55071. //
  55072. // Utilities
  55073. //
  55074. GLTFLoaderExtension._Extensions = [];
  55075. return GLTFLoaderExtension;
  55076. }());
  55077. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  55078. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  55079. })(BABYLON || (BABYLON = {}));
  55080. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  55081. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  55082. var BABYLON;
  55083. (function (BABYLON) {
  55084. var GLTF2;
  55085. (function (GLTF2) {
  55086. var Extensions;
  55087. (function (Extensions) {
  55088. var MSFTLOD = (function (_super) {
  55089. __extends(MSFTLOD, _super);
  55090. function MSFTLOD() {
  55091. return _super !== null && _super.apply(this, arguments) || this;
  55092. }
  55093. Object.defineProperty(MSFTLOD.prototype, "name", {
  55094. get: function () {
  55095. return "MSFT_lod";
  55096. },
  55097. enumerable: true,
  55098. configurable: true
  55099. });
  55100. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  55101. if (!material.extensions) {
  55102. return false;
  55103. }
  55104. var properties = material.extensions[this.name];
  55105. if (!properties) {
  55106. return false;
  55107. }
  55108. // Clear out the extension so that it won't get loaded again.
  55109. material.extensions[this.name] = undefined;
  55110. // Tell the loader not to clear its state until the highest LOD is loaded.
  55111. var materialLODs = [material.index].concat(properties.ids);
  55112. loader.addLoaderPendingData(material);
  55113. for (var index = 0; index < materialLODs.length; index++) {
  55114. loader.addLoaderNonBlockingPendingData(index);
  55115. }
  55116. // Start with the lowest quality LOD.
  55117. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  55118. return true;
  55119. };
  55120. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  55121. var _this = this;
  55122. var materialLOD = loader.gltf.materials[materialLODs[lod]];
  55123. if (lod !== materialLODs.length - 1) {
  55124. loader.blockPendingTracking = true;
  55125. }
  55126. loader.loadMaterial(materialLOD, function (babylonMaterial, isNew) {
  55127. assign(babylonMaterial, isNew);
  55128. loader.removeLoaderPendingData(lod);
  55129. // Loading is considered complete if this is the lowest quality LOD.
  55130. if (lod === materialLODs.length - 1) {
  55131. loader.removeLoaderPendingData(material);
  55132. }
  55133. if (lod === 0) {
  55134. loader.blockPendingTracking = false;
  55135. return;
  55136. }
  55137. // Load the next LOD when the loader is ready to render and
  55138. // all active material textures of the current LOD are loaded.
  55139. loader.executeWhenRenderReady(function () {
  55140. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  55141. setTimeout(function () {
  55142. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  55143. }, MSFTLOD.MinimalLODDelay);
  55144. });
  55145. });
  55146. });
  55147. };
  55148. /**
  55149. * Specify the minimal delay between LODs in ms (default = 250)
  55150. */
  55151. MSFTLOD.MinimalLODDelay = 250;
  55152. return MSFTLOD;
  55153. }(GLTF2.GLTFLoaderExtension));
  55154. Extensions.MSFTLOD = MSFTLOD;
  55155. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  55156. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  55157. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  55158. })(BABYLON || (BABYLON = {}));
  55159. //# sourceMappingURL=MSFT_lod.js.map
  55160. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  55161. var BABYLON;
  55162. (function (BABYLON) {
  55163. var GLTF2;
  55164. (function (GLTF2) {
  55165. var Extensions;
  55166. (function (Extensions) {
  55167. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  55168. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  55169. function KHRMaterialsPbrSpecularGlossiness() {
  55170. return _super !== null && _super.apply(this, arguments) || this;
  55171. }
  55172. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  55173. get: function () {
  55174. return "KHR_materials_pbrSpecularGlossiness";
  55175. },
  55176. enumerable: true,
  55177. configurable: true
  55178. });
  55179. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  55180. if (!material.extensions) {
  55181. return false;
  55182. }
  55183. var properties = material.extensions[this.name];
  55184. if (!properties) {
  55185. return false;
  55186. }
  55187. loader.createPbrMaterial(material);
  55188. loader.loadMaterialBaseProperties(material);
  55189. this._loadSpecularGlossinessProperties(loader, material, properties);
  55190. assign(material.babylonMaterial, true);
  55191. return true;
  55192. };
  55193. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, material, properties) {
  55194. var babylonMaterial = material.babylonMaterial;
  55195. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  55196. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  55197. babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  55198. if (properties.diffuseTexture) {
  55199. babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  55200. loader.loadMaterialAlphaProperties(material);
  55201. }
  55202. if (properties.specularGlossinessTexture) {
  55203. babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  55204. babylonMaterial.reflectivityTexture.hasAlpha = true;
  55205. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  55206. }
  55207. loader.loadMaterialAlphaProperties(material, properties.diffuseFactor);
  55208. };
  55209. return KHRMaterialsPbrSpecularGlossiness;
  55210. }(GLTF2.GLTFLoaderExtension));
  55211. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  55212. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  55213. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  55214. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  55215. })(BABYLON || (BABYLON = {}));
  55216. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  55217. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  55218. module.exports = BABYLON;
  55219. };